Working with JSON Data in Python
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It is easy for humans to read and write and easy for machines to parse and generate. Due to its simplicity and flexibility, JSON has become the de facto standard for data exchange in web APIs and configuration files.
A JSON object consists of key-value pairs, similar to a Python dictionary.
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"courses": [
{ "title": "History", "credits": 3 },
{ "title": "Math", "credits": 4 }
]
}The json Module
Python has an excellent built-in json module that makes working with JSON data seamless. It handles the conversion (or “translation”) between Python objects and JSON strings.
Python to JSON Translation Table
| Python Object | JSON Equivalent |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
To use the module, you must first import it: import json.
Serialization: Converting Python to JSON
Serialization is the process of converting a Python object into a JSON formatted string. The json module provides two functions for this.
json.dumps(): Serialize to a String
The dumps() function (short for “dump string”) takes a Python object and returns a JSON formatted string. This is useful when you need to send JSON data over a network or work with it as a string in your program.
Pyground
Convert a Python dictionary into a JSON string.
Expected Output:
Type of result: <class 'str'>
JSON String: {"user": "jane_doe", "permissions": ["read", "write"], "active": true, "login_attempts": null}Output:
Making JSON Readable with indent
The JSON produced by default is compact and not very human-readable. Both dump() and dumps() have an indent argument that you can use to “pretty-print” the JSON.
Pyground
Save the `config.json` file again, but this time with an indent of 4 spaces.
Expected Output:
Data saved to config_pretty.json with indentation.
Output:
Check the config_pretty.json file. You’ll see it’s nicely formatted, making it much easier to read!
Deserialization: Converting JSON to Python
Deserialization is the reverse process: parsing a JSON formatted string or file and converting it back into a Python object.
json.loads(): Deserialize from a String
The loads() function (short for “load string”) takes a JSON formatted string and returns a Python object (usually a dictionary).
Pyground
You receive a JSON string from an API. Parse it into a Python dictionary.
Expected Output:
Type of result: <class 'dict'>\nProduct ID: 101\nIs it in stock? True
Output:
Understanding how to serialize and deserialize JSON data in Python is crucial for working with web APIs, configuration files, and data interchange between systems. With the json module, this process is straightforward and efficient.