1 min read

Python JSON Module

The json module provides an API for parsing and creating JSON (JavaScript Object Notation). It is very similar to the pickle and marshal modules but uses a text-based format that is language-independent.

Importing the Module

import json

Parsing JSON (Decoding)

From a String

Use json.loads() to parse a JSON string into a Python dictionary or list.

import json

json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)

print(data["name"]) # Output: John

From a File

Use json.load() to read from a file object.

with open('data.json', 'r') as f:
    data = json.load(f)

Generating JSON (Encoding)

To a String

Use json.dumps() to convert a Python object into a JSON string.

import json

data = {
    "name": "Jane",
    "age": 25,
    "is_student": False
}

json_string = json.dumps(data)
print(json_string)

Pretty Printing

You can make the output more readable by using the indent parameter.

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

programming/python/python