8

I was wondering if it possible to use the attrs library to convert nested JSONs to Python class instances so that I can access attributes in that JSON via dot notation (object.attribute.nested_attribute).

My JSONs have a fixed schema, and I would be fine with having to define the classes for that schema manually, but I'm not sure if it would be possible to turn the JSON into the nested class structure without having to instantiate every nested object individually. I'm basically looking for a fromdict() function that knows (based on the keys) which class to turn a JSON object into.

(I also know that there are other ways to build 'DotDicts', but these seem always a bit hacky to me and would probably need thorough testing to verify that they work correctly.)

gmolau
  • 2,815
  • 1
  • 22
  • 45
  • @deceze I said that I know of these other approaches, I was specifically asking about a way to do this within the attrs framework. Would you mind reading the question before slapping a 'duplicate' onto it? – gmolau Feb 15 '18 at 13:55
  • 1
    @user8793 in that case, I would advise you: please update your question with the restrictions you have which would limit you to use attrs. As good answers are given in the duplicate link provided, which will provide you with exactly the object structure you are requesting. – Edwin van Mierlo Feb 15 '18 at 13:58
  • @deceze attrs (http://www.attrs.org/en/stable/index.html) is a library to simplify working with Python classes. I'm sorry, but why don't you just move on if don't even know what the question is about? – gmolau Feb 15 '18 at 14:00
  • It would have helped if you simply mentioned the word "library" or "framework" in your question to avoid such confusion. For the record, I wasn't the only one confused by that, I acted on a suggested duplicate. Consider that your question may not be clear, don't blame everything on incompetence. – deceze Feb 15 '18 at 14:02
  • @EdwinvanMierlo I said that I don't trust these approaches (building a 'DotDict' class by hand) to really cover all the edge cases that can occur in production settings. Since attrs is a well established project with the specific goal to cover all these edge cases I was wondering if it could be adapted to (or does already) work with JSONs. – gmolau Feb 15 '18 at 14:05
  • @deceze If you are marking a question is duplicate it is your responsibility to positively verify that you have understood it correctly. – gmolau Feb 15 '18 at 14:10

1 Answers1

9

The attrs wiki currently has two serialization libraries:

  1. cattrs
  2. and related.

With cattrs being maintained by one of attrs’ most prolific contributors.

I know that some people mention integrations with other systems too. At this point it's unlikely that attrs will grow an own solution since the externally developed look pretty good.

vincent
  • 6,368
  • 3
  • 25
  • 23
hynek
  • 3,647
  • 1
  • 18
  • 26