Parse JSON in Python

26 Dec 2014

JSON is a commonly used data exchange format over the Web. For Python programming language, JSON data format is already very similar to Python dictionary, which makes parsing JSON in Python very convenient.

A handy Python module json already exists for such purpose. For basic usage, the most important methods are dumps and loads. dumps means dumping python object into JSON string representation; loads is the reverse of dumps, which loads JSON string representation into a Python object.

Here are some examples how you can use these two methods:

>>> import json

# dumps: python object -> json string
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

# loads: json string -> python object
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

That’s it! This is how simple it is!

Be aware that JSON format only accepts double-quoted strings as its keys, and for its values, it accepts only Number (int long float), String (str unicode), Boolean (True False), Array (list tuple), Object (dict) and Null (None).

That means just arbitrary Python objects cannot be turned into a JSON with json.dumps; they need to be convered by hand (with some codes) into combinations of the Python data types mentioned in the previous paragraph before feeding them into dumps.