Python simplejson tutorial

Python simplejson tutorial shows how to read and write JSON data with Python simplejson module.

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easily read and written by humans and parsed and generated by machines. The application/json is the official Internet media type for JSON. The JSON filename extension is .json.

The simplejson module

The simplejson is simple, fast, complete, and extensible JSON encoder and decoder for Python 2.5+ and Python 3.3+. It is pure Python code with no dependencies.

The simplejson module is included in modern Python versions. The decoder can handle incoming JSON strings of any specified encoding (UTF-8 by default)

Using simplejson

import json

To use simplejson module, we import json.

Simplejson conversion table

The following table shows how data types are converted between Python and JSON.

PythonJSON
dict, namedtupleobject
list, tuplearray
str, unicodestring
int, long, floatnumber
Truetrue
Falsefalse
Nonenull

The json.dump()

The json.dump() method serializes Python object as a JSON formatted stream to a file object.

simplejson_dump.py
#!/usr/bin/python

import json

data = {"name": "Jane", "age": 17}

with open('friends.json', 'w') as f:
    
    json.dump(data, f)

The example serializes a Python dictionary into JSON with json.dump() method. The JSON data is written to friends.json file.

$ cat friends.json 
{"age": 17, "name": "Jane"}

After executing the script, we have this data.

The json.dumps()

The json.dumps() method serializes Python object to a JSON string.

simplejson_dumps.py
#!/usr/bin/python

import json

data = [{"name": "Jane", "age": 17}, {"name": "Thomas", "age": 27}]

json_data = json.dumps(data)
print(repr(json_data))

The example serializes a Python list into JSON string with json.dumps() method. The JSON data is printed to the console.

$ ./simplejson_dumps.py 
'[{"name": "Jane", "age": 17}, {"name": "Thomas", "age": 27}]'

This is the output of the example.

The json.load()

The json.load() method deserializes a file object containing a JSON document to a Python object.

config.json
{
  "theme" : "bluespring",
  "size": "small",
  "splashscreen": "false"
}

The config.json file contains this data.

read_config.py
#!/usr/bin/python

import json

with open('config.json') as f:

    config = json.load(f)
    
    print('Theme: {}'.format(config['theme']))
    print('Size: {}'.format(config['size']))
    print('Splash screen: {}'.format(config['splashscreen']))

The example reads configuration data from config.json file with json.load() and prints the data to the terminal.

$ ./read_config.py 
Theme: bluespring
Size: small
Splash screen: false

This is the output.

The json.loads()

The json.loads() method deserializes a JSON string to a Python object.

simplejson_loads.py
#!/usr/bin/python

import json

json_data = '{"name": "Jane", "age": 17}'

data = json.loads(json_data)

print(type(json_data))
print(type(data))

print(data)

The example deserializes a JSON string into a Python dictionary.

$ ./simple.py 
<class 'str'>
<class 'dict'>
{'name': 'Jane', 'age': 17}

This is the output of the example.

Simplejson read JSON from URL

The following example reads JSON data from a web page. We get JSON data from http://time.jsontest.com.

$ curl http://time.jsontest.com
{
   "time": "10:00:19 AM",
   "milliseconds_since_epoch": 1496311219347,
   "date": "06-01-2017"
}

A GET request to this site returns this JSON string.

parse_json_url.py
#!/usr/bin/python

import json
import urllib.request

hres = urllib.request.urlopen('http://time.jsontest.com')

data = json.loads(hres.read().decode("utf-8"))

print('Unix time: {}'.format(data['milliseconds_since_epoch']))
print('Time: {}'.format(data['time']))
print('Date: {}'.format(data['date']))

In the example, we use urllib.request module to create a request to the web site.

data = json.loads(hres.read().decode("utf-8"))

From the returned response, we transform the JSON string into a Python dictionary with json.loads() method.

print('Unix time: {}'.format(data['milliseconds_since_epoch']))
print('Time: {}'.format(data['time']))
print('Date: {}'.format(data['date']))

With the help of Python's format() method, we print the retrieved data to the console.

$ ./parse_json_url.py 
Unix time: 1496311518866
Time: 10:05:18 AM
Date: 06-01-2017

This is the output.

Pretty printing

With simplejson we can easily pretty print our data.

pretty_print_json.py
#!/usr/bin/python

import json

json_data = {"name":"Audi", "model":"2012", "price":22000, 
                 "colours":["gray", "red", "white"]}

data = json.dumps(json_data, sort_keys=True, indent=4 * ' ')

print(data)

With sort_keys and indent options we nicely format the JSON data.

$ ./pretty_print_json.py 
{
    "colours": [
        "gray",
        "red",
        "white"
    ],
    "model": "2012",
    "name": "Audi",
    "price": 22000
}

This is the output of the example. The data is indented and the keys are sorted.

Simplejson custom class

Simplejson serializes and deserializes only a few Python objects, which are listed in the conversion table. For custom Python objects, we need to do some additional steps.

custom_class.py
#!/usr/bin/python

import json

class Person(object):
    
    def __init__(self, name, age):
    
        self.name = name
        self.age = age
        
p = Person("Lucy", 23) 

json_data = json.dumps(p.__dict__)

print(repr(json_data))

In this example, we serialize a custom object into JSON.

json_data = json.dumps(p.__dict__)

The trick is to use the __dict__ attribute, which stores the object attributes (name and age).

$ ./custom_class.py 
'{"name": "Lucy", "age": 23}'

This is the output.

Simplejson list of custom classes

In the next example, we show how to serialize a list of custom classes.

custom_class_list.py
#!/usr/bin/python

import json

class Person(object):
    
    def __init__(self, name, age):
    
        self.name = name
        self.age = age
        
    def toJson(self):
        '''
        Serialize the object custom object
        '''
        return json.dumps(self, default=lambda o: o.__dict__, 
                sort_keys=True, indent=4)            

p1 = Person("Lucy", 23) 
p2 = Person("Thomas", 29)

people = []
people.append(json.loads(p1.toJson()))
people.append(json.loads(p2.toJson()))

json_data = json.dumps(people)

print(repr(json_data))

We have created a toJson() method that serializes the object.

people = []
people.append(json.loads(p1.toJson()))
people.append(json.loads(p2.toJson()))

We call the toJson() method when we add the objects to the list.

$ ./custom_class_list.py 
'[{"age": 23, "name": "Lucy"}, {"age": 29, "name": "Thomas"}]'

This is the output of the example.

In this tutorial, we have worked with the Python simplejson library.

You might also be interested in the following related tutorials: Python tutorial, Python list comprehensions, Pyquery tutorial, Openpyxl tutorial, Python requests tutorial, and Python CSV tutorial.