JSON conversion

Vegeedog
Basic Python notes
Published in
3 min readAug 10, 2021

--

Dictionary → JSON format

json.dumps( dictionary, …) — convert into a json object

json.dump(dictionary, file, …) — write into a json file

We get the output from the 7th line:

And check in the person.json file and find

JSON format → Dictionary

json.loads( JSON object, …) — convert into a python dictionary

json.load( JSON file, …) — read the json object, and convert it into a python dictionary

We get the output from the 9th line & 14th line, which are the same.

The default conversion is between python dictionary & json object

So the next would be about how to deal with other data types.

Other data types → JSON format

For instance, we have a self-defined class named “User.”

if we directly use the dumps method, it would show a type error, because the given data type is not a dictionary.

Instead, we have 2 ways to deal with it.

  1. Define a new method to overwrite the default encoding method

json.dumps(user, default= self-defined encoding method, ….)

Output from 22nd line:

2. Create a self-defined encoder class, inheriting the JSONEncoder class.

MyEncoder.encode( object )

At the 23th line, we create an instance of this customized JSONEncoder, and then, use it to encode the “user” object. If the given argument is not of User type, then it would use the default JSONEncoder to encode it.

Output:

JSON format → Other data types

When we use the json.load method, it would only convert json into dictionary.

In order to convert to other data types, the way is similar to the 1st way of the last part, which is, write a new method and pass it to the json.load method.

On the 26th line, we define the new method to convert a dictionary into the desired data type.

And then, on the 31st line, we assign the object_hook to this method.

Output from 32nd & 33th line:

--

--