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”]


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”]

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.




About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps Developer in in Public/Private cloud domain. my @github : my @nagiosexchange : my @linkedin :☁-a9415615
This entry was posted in ARTICLES, HOWTO, Programming, SCRIPTING, TIPS & T RICS, TUTORIALS, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s