Simple Json Manipulation using Python

We list the top json related operations which include load, loads, dump, dumps and pretty-print json. 

Create a json file from a python dictionary

We can easily store a python dictionary into a json file using the json dump method. In the following code, we first define a dictionary, then transfer that dictionary into a json file:

The content of my.json file looks like this:


How to pretty-print JSON?

You can run python with the json.tool  option to build a more readable json file: prettyprint json. 

Now my_pretty.json looks like this:

Convert a dictionary into a json string

We can use the dumps method to convert a dictionary into a json string. See the following code:

Create a json object from a file

We can easily use the load method create a json object from a file:

Creat a json object from a string

Suppose you already have a json string, you can easily create a json object using the loads method: