Read and write json in python

In todays  world json is one of the easiest method of communication to exchange data.

Its used everywhere Cloud APIs, Databases, Configuration files, REST Call.

So below are the steps how to read and write back to a json file using python.

Lets say: test.json contains:

{
“pro”: “Cloud”,
“fname”: “Priyadarshee”,
“yob”: 1988
}

To load and read  this file in python:

>>> import json
>>> config = json.loads(open(“test.json”).read())
>>> config
{u’pro’: u’Cloud’, u’yob’: 1988, u’fname’: u’Priyadarshee’}

>>> config[“pro”]
u’Cloud’

 

Now adding new key-value pair as well as updating existing pair:

>>> config [“lname”] = “Kumar”
>>> config [“pro”] = “DevOps”
>>>
>>> config
{‘lname’: ‘Kumar’, u’pro’: ‘DevOps’, u’yob’: 1988, u’fname’: u’Priyadarshee’}
>>> json.dump(config,open(“test.json”,”w”),indent=4)
>>> config[“pro”]
u’DevOps’

Here indent = 4, makes the indentation with 4 spaces. It can be adjusted as required.

New test.josn will look like:

cat test.json

{
“lname”: “Kumar”,
“pro”: “DevOps”,
“yob”: 1988,
“fname”: “Priyadarshee”
}

We can use this lines in a python script to make a complete code to use as required.

 

 

Leave a Reply