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.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import jsonjson_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

