ZetCode

Python simplejson

last modified January 29, 2024

In this article we show 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.

json_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.

json_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.

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

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

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}

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
{
    "date": "08-08-2023",
    "milliseconds_since_epoch": 1691506979261,
    "time": "03:02:59 PM"
 }

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: 1691507071395
Time: 03:04:31 PM
Date: 08-08-2023

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
}

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:

    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}'

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:

    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"}]'

Source

Python json — JSON encoder and decoder

In this article we have worked with the Python simplejson library.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Python tutorials.