Computer Science Atlas
Snippets

Python 3: JSON

April 30, 2021|Updated May 1, 2021
 
Table of Contents

Python 3 comes with a built-in json module that handles encoding (serializing) and decoding (deserializing) Python data to and from JSON.

Encode (Serialize) as JSON

Output as JSON String: dumps()

Compact Format

To encode (serialize) Python data as a JSON string, we can use the built-in json.dumps() function (the s at the end of the name stands for "string" as in "dump string"):

import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

data_json = json.dumps( data )

print( data_json )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

data_json = json.dumps( data )

print( data_json )

This will output the JSON in a compact format:

{"str": "value", "list": [1, 2, 3, 4], "dict": {"a": "b"}}

Pretty Print

We can pretty print the output (make the output more human-readable) by adding indentation and sorting the keys:

import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

data_json = json.dumps( data, indent=4, sort_keys=True )

print( data_json )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

data_json = json.dumps( data, indent=4, sort_keys=True )

print( data_json )

The output now looks like:

{
    "dict": {     
        "a": "b"  
    },
    "list": [     
        1,        
        2,        
        3,        
        4
    ],
    "str": "value"
}

Output JSON to File: dump()

Compact Format

The examples above stored the JSON output to a string called data_json. If we want to save the JSON as a file, we could first output to a string and then save it to a file. But the json module provides us with another function json.dump() (there is no s at the end) that lets us do that in one step:

import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

# Save as mydata-compact.json using json.dump().
with open( 'mydata-compact.json', 'w' ) as json_file:
    data_json = json.dump( data, json_file )

# Show the file contents on screen.
with open( 'mydata-compact.json', 'r' ) as json_file:
    print( json_file.read() )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

# Save as mydata-compact.json using json.dump().
with open( 'mydata-compact.json', 'w' ) as json_file:
    data_json = json.dump( data, json_file )

# Show the file contents on screen.
with open( 'mydata-compact.json', 'r' ) as json_file:
    print( json_file.read() )

open( 'mydata.json', 'w' ) opens a file called mydata.json in the script user's current directory (creating it if it doesn't already exist) for writing text output ('w'). The file can be referenced by the variable json_file, which is passed to json.dump() for writing.

The second argument to json.dump() doesn't have to be an actual file on the file system — it can actually be any file-like object such as io.StringIO.

Pretty Print

We can use indent and sort_keys with dump() just as we did with dumps() to pretty print the output:

import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

# Save as mydata-pretty.json using json.dump().
with open( 'mydata-pretty.json', 'w' ) as json_file:
    data_json = json.dump( data, json_file, indent=4, sort_keys=True )

# Show the file contents on screen.
with open( 'mydata-pretty.json', 'r' ) as json_file:
    print( json_file.read() )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import json

data = {
    'str': 'value',
    'list': [1, 2, 3, 4],
    'dict': { 'a': 'b' },
}

# Save as mydata-pretty.json using json.dump().
with open( 'mydata-pretty.json', 'w' ) as json_file:
    data_json = json.dump( data, json_file, indent=4, sort_keys=True )

# Show the file contents on screen.
with open( 'mydata-pretty.json', 'r' ) as json_file:
    print( json_file.read() )

Decode (Deserialize / Parse) from JSON

From JSON String

We can go the other direction and decode (deserialize / parse) a JSON string using json.loads() (the s at the end of the name stands for "string" as in "load string")

import json

data_json = '{"str": "value", "list": [1, 2, 3, 4], "dict": {"a": "b"}}'

data = json.loads( data_json )

print( data )
1
2
3
4
5
6
7
import json

data_json = '{"str": "value", "list": [1, 2, 3, 4], "dict": {"a": "b"}}'

data = json.loads( data_json )

print( data )

From JSON File

As with dump() for encoding, we can decode a JSON file directly using load():

import json

with open( 'mydata-compact.json', 'r' ) as json_file:
    data = json.load( json_file )

print( data )
1
2
3
4
5
6
import json

with open( 'mydata-compact.json', 'r' ) as json_file:
    data = json.load( json_file )

print( data )

References