The json Module
On this page
JSON in PythonParse JSON — Convert from JSON to PythonConvert from Python to JSONFormatting the ResultThe json module allows you to work with JSON data—a lightweight format widely used for sharing data between systems and APIs.
It helps you convert between Python objects and JSON text easily.
JSON in Python
JSON (JavaScript Object Notation) represents data as text but looks similar to Python dictionaries. This makes conversion between the two very natural in Python.
Parse JSON — Convert from JSON to Python
json.loads() parses JSON text into the corresponding Python values: an object becomes a dictionary, an array becomes a list, and scalar values become the corresponding Python scalars. Here the input is an object:
import json
data = '{"name": "Alice", "age": 25, "city": "Paris"}'
person = json.loads(data)
print(person["city"])Output
Paris
Convert from Python to JSON
You can use json.dumps() to turn Python data structures into JSON strings.
student = {
"name": "Bob",
"age": 22,
"courses": ["Math", "AI"]
}
json_string = json.dumps(student)
print(json_string)Output
{"name": "Bob", "age": 22, "courses": ["Math", "AI"]}
Formatting the Result
You can make JSON output more readable by adding indentation and sorting keys.
print(json.dumps(student, indent=4, sort_keys=True))Output
{
"age": 22,
"courses": [
"Math",
"AI"
],
"name": "Bob"
}
The json module is essential for saving configurations, web communication, and data storage.