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:
|
1 2 3 4 5 6 7 8 9 10 11 |
import json mydict = {} mydict['a'] = 'aa' mydict['b'] = ['bb1', 'bb2'] mydict['c'] = {'cc':'cccc', 'dd': 'dddd'} f = open('my.json', 'w') json.dump(mydict, f) f.close() |
The content of my.json file looks like this:
|
1 |
{"a": "aa", "c": {"cc": "cccc", "dd": "dddd"}, "b": ["bb1", "bb2"]} |
How to pretty-print JSON?
You can run python with the json.tool option to build a more readable json file: prettyprint json.
|
1 |
python -m json.tool my.json > my_pretty.json |
Now my_pretty.json looks like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
$ cat my_pretty.json { "a": "aa", "b": [ "bb1", "bb2" ], "c": { "cc": "cccc", "dd": "dddd" } } |
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:
|
1 2 3 4 5 6 7 8 9 10 |
import json mydict = {} mydict['a'] = 'aa' mydict['b'] = ['bb1', 'bb2'] mydict['c'] = {'cc':'cccc', 'dd': 'dddd'} json_str = json.dumps(mydict) print json_str # {"a": "aa", "c": {"cc": "cccc", "dd": "dddd"}, "b": ["bb1", "bb2"]} |
Create a json object from a file
We can easily use the load method create a json object from a file:
|
1 2 3 4 5 6 7 8 |
import json fp = open('my.json', 'r') json_obj = json.load(fp) fp.close() print json_obj['b'] # [u'bb1', u'bb2'] |
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:
|
1 2 3 4 5 6 7 |
import json json_string = """{"a": "aa", "c": {"cc": "cccc", "dd": "dddd"}, "b": ["bb1", "bb2"]} """ json_obj = json.loads(json_string) print json_obj['b'] # [u'bb1', u'bb2'] |











