How to parse JSON string in Python

When developing a web service, you may often rely on a JSON-based web service protocol. If you are using Python for that, it is straightforward to deal with JSON-formatted messages due to its extensible modules. For example, Python's JSON module which was introduced in Python 2.6 provides default JSON encoder and decoder in Python. There are also other JSON encoder/decoder that you can install and use (e.g., simplejson).

In this tutorial, I will describe how to parse JSON in Python with JSON module.

The following code snippet is an example of parsing JSON in Python.

import json

json_input = '{ "one": 1, "two": { "list": [ {"item":"A"},{"item":"B"} ] } }'

try:
    decoded = json.loads(json_input)

    # pretty printing of json-formatted string
    print json.dumps(decoded, sort_keys=True, indent=4)

    print "JSON parsing example: ", decoded['one']
    print "Complex JSON parsing example: ", decoded['two']['list'][1]['item']

except (ValueError, KeyError, TypeError):
    print "JSON format error"

The above Python example will print out the following.

{
    "one": 1,
    "two": {
        "list": [
            {
                "item": "A"
            },
            {
                "item": "B"
            }
        ]
    }
}
JSON parsing example:  1
Complex JSON parsing example:  B

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

2 thoughts on “How to parse JSON string in Python

Leave a comment

Your email address will not be published. Required fields are marked *

Current ye@r *