JSON encoding and decoding with Python


Introduction
JSON (JavaScript Object Notation) is frequently used between a server and a web application. An example of JSON data:

{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian"
        }, 
        {
            "city": "Amsterdam", 
            "name": "David"
        }
    ]
}

The json module enables you to convert between JSON and Python Objects.

JSON conversion examples

Convert JSON to Python Object (Dict)
To convert JSON to a Python dict use this:

import json
 
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print python_obj["name"]
print python_obj["city"]

Convert JSON to Python Object (List)
JSON data can be directly mapped to a Python list.

import json
 
array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)
 
for element in data['drinks']:
    print element

Convert JSON to Python Object (float)
Floating points can be mapped using the decimal library.

import json
from decimal import Decimal
 
jsondata = '{"number": 1.573937639}'
 
x = json.loads(jsondata, parse_float=Decimal)
print x['number']

Convert JSON to Python Object (Example)
JSON data often holds multiple objects, an example of how to use that below:

import json
 
json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }'
 
try:
    decoded = json.loads(json_input)
 
    # Access data
    for x in decoded['persons']:
        print x['name']
 
except (ValueError, KeyError, TypeError):
    print "JSON format error"

Convert Python Object (Dict) to JSON
If you want to convert a Python Object to JSON use the json.dumps() method.

import json
from decimal import Decimal
 
d = {}
d["Name"] = "Luke"
d["Country"] = "Canada"
 
print json.dumps(d, ensure_ascii=False)
# result {"Country": "Canada", "Name": "Luke"}

Converting JSON data to Python objects 
JSON data can be converted (deserialized) to Pyhon objects using the json.loads() function.  A table of the mapping:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Pretty printing

If you want to display JSON data you can use the json.dumps() function.

import json
 
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print json.dumps(python_obj, sort_keys=True, indent=4)

More
Google Charts with JSON data


2 thoughts on “JSON encoding and decoding with Python

  1. Jeremy Lee - May 23, 2015

    Warning: do not name your test file json.py (it’s tempting for some reason). In general, don’t name your source the same as pre-defined imported modules. The import looks in the local directory first.

    1. Frank - May 23, 2015

      Correct, you cannot name your file json.py because we import json. This is the general case in python and can be confusing. Thanks for your comment