Python build object from json and back

Suppose you need to have bilateral conversion from json to object and vice versa.

So, in this article you’ll find out how to:

  • convert json to object python
  • convert object to json python
  • build object from json python

Build object from json

import json
import YourObject from your_file

json_string = "<paste_json_string_here>"
json_object = json.loads(json_string)
u = YourObject(**json_object)

Convert object to json

import json
import YourObject from your_file

your_object = YourObject(
  propertyName1="value1",
  propertyName2="value2",
  additionalProperties={
    "additionalProperty1": "123",
    "additionalProperty1": "example_2"
  },
)

json_string = json.dumps(your_object, default=lambda o: o.__dict__)
print(json_string)

If you need to rename some of the properties in the target json, you can make it this way:

json_string.replace("additional_property1", "additionalProperty1")

Here you go!


Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝