Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attrs to turn JSONs into Python classes

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.)

like image 572
gmolau Avatar asked Feb 15 '18 13:02

gmolau


People also ask

How do I convert JSON to Python?

Parse JSON - Convert from JSON to Python If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

How do you serialize a JSON file in Python?

The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.

What is ATTR S in Python?

attrs is the Python package that will bring back the joy of writing classes by relieving you from the drudgery of implementing object protocols (aka dunder methods). Trusted by NASA for Mars missions since 2020! Its main goal is to help you to write concise and correct software without slowing down your code.

How do you Jsonify an object in Python?

Conversion of the class object to JSON is done using json package in Python. json. dumps() converts Python object into a json string.


Video Answer


1 Answers

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.

like image 96
hynek Avatar answered Sep 29 '22 23:09

hynek