How to parse JSON string in Python

Last updated on October 20, 2020 by Dan Nanni

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

If interested, you can check out other tutorials on parsing JSON string, such as using Perl language or a Linux command line.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal (Credit Card) or Bitcoin (1M161JGAkz3oaHNvTiPFjNYkeABox8rb4g).

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean