Python JSON Tutorial

The JSON module is part of the Python standard library and provides an easy to use way of dealing with JSON data types. This tutorial servers as a basic introduction to this very useful module.

Python to JSON table

The first place to start is the Python to JSON table (defined in the documentation) which details how Python data structures map to JSON and vice versa.

Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null

As the above table states, dictionaries convert to objects and objects to dictionaries. So let’s see some examples.

JSON to Python

import json
json_string = '{"name": "Boba Fett", "profession":"Bounty Hunter"}'
json_object = json.loads(json_string)
print json_object
print json_object["name"]
print json_object["profession"]

In this example we have our simple JSON string and by calling json.loads we deserialise it to a Python dict just as the table said. Once we have the dictionary we can then access attributes of the object as we would any dictionary. Here’s the output of the above script.

{u'profession': u'Bounty Hunter', u'name': u'Boba Fett'}
Boba Fett
Bounty Hunter

Python to JSON

Now let’s look at the opposite direction.

import json
json_object = {"name": "Boba Fett", "profession": "Bounty Hunter"}
print(json.dumps(json_object))

Here we’ve created a simple dictionary containing the same information as our previous json_string. The output is as follows;

{"profession": "Bounty Hunter", "name": "Boba Fett"

An Array of Objects

import json
json_string = '{"servers": [' \
              '{"name": "test1"},' \
              '{"name":"test2"},' \
              '{"name":"test3"},' \
              '{"name":"test4"}]}'
json_object = json.loads(json_string)
print json_object["servers"][2]["name"]

In this case we have an object which is a list of objects which is serialised to a dictionary, containing a list, containing more dictionaries. To get the name of the 3rd item in the list we just specify the key of the enclosing object, the index in the list and the key of the attribute we want. The output of this script is simply “test3”.

Conclusion

These were only a few simple examples of what you can do with the JSON module, but hopefully they provided a useful starting point. For more information the documentation is available here.

 

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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