We can easily convert any Python class object to JSON format using json.dumps() method.

Syntax:

where object.__dict__ is the dictionary representation of Python object.

json inspired by javascript is a Python inbuilt module used to work with JSON data.

Example: Convert Python Class Object to JSON

Let’s convert a python object into JSON in code.

output

json.dumps() accept python dictionary as an argument, so we pass the dictionary representation of the object using its __dict__ attribute.

Example: Convert JSON String to Python Object

We can easily convert a JSON string into python object using json.loads() method and python varargs.

Syntax:

json.loads() return dictionay form of JSON String, which we can use it to construct python object.

Let’s see an example of converting JSON string to Python object in code.

output

Remember, json.load() and json.loads() are two different method.

  • json.load() read JSON encoded data and convert it into Python dictionary.
  • json.loads() parse JSON string into Python dictionary.

If you have any doubts or suggestion then please comment below.

Leave a Reply