JSON in Python is a standard format for representing structured data using key-value pairs, arrays, and nested objects. Python's built-in json module enables reading, writing, and manipulating JSON data as native Python dictionaries and lists.
When working with APIs, configuration files, or web services, JSON is the most common format for exchanging data between systems. Python treats JSON as a string until explicitly parsed into a dictionary or list using the json.loads() function. This allows smooth integration with Python's data structures.
For example, a JSON string like {"name": "Alice", "age": 30, "skills": ["Python", "APIs"]} becomes a Python dictionary after parsing. The reverse process-converting a dictionary back to JSON-is handled by json.dumps().
Python's json module provides two core functions: loads() for parsing strings and dumps() for serializing Python objects. These functions handle conversion between JSON text and native Python data types.
When json.loads() processes a valid JSON string, it returns a dictionary if the input starts with { or a list if it begins with [. For example:
import json
data = '{"temperature": 23.5, "location": "New York"}'
parsed = json.loads(data)
print(type(parsed)) # <class 'dict'>
print(parsed["temperature"]) # 23.5
Similarly, json.dumps() converts a dictionary into a JSON-formatted string. This is useful when sending data to a server or saving to a file.
When handling files, use json.load() and json.dump() instead. These functions read from and write to file-like objects, avoiding manual string handling.
JSON supports four basic types: strings, numbers, booleans, and null. Nested structures include objects (key-value maps) and arrays (ordered lists).
| JSON Type | Python Equivalent | Example |
|---|---|---|
| String | str | "hello" |
| Number | int or float | 42, 3.14 |
| Boolean | bool | true, false |
| Null | None | null |
| Object | dict | {"key": "value"} |
| Range | list | [1, 2, 3] |
JSON does not support tuples, sets, or custom classes. Any attempt to serialize such types raises a TypeError. To work around this, define a custom encoder function using the default parameter in json.dumps().
A common mistake is assuming JSON supports dates. While ISO 8601 timestamps are valid JSON strings, Python's datetime objects are not natively serializable. You must convert them to strings manually or use a custom encoder.
JSON is widely used in REST APIs, configuration files, and data exchange between microservices. A typical workflow involves receiving a JSON response from an API, parsing it, extracting values, and processing them.
For example, when fetching weather data from an API:
import requests
import json
response = requests.get("https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41¤t=temperature_2m")
data = json.loads(response.text)
print(f"Current temperature: {data['current']['temperature_2m']}°C")
This code retrieves a JSON response, parses it, and prints the current temperature. Without proper error handling, malformed JSON causes a json.JSONDecodeError. Always wrap json.loads() in a try-except block.
Another frequent issue is mixing JSON syntax with Python syntax. For example, using single quotes in a JSON string causes a parse failure. JSON requires double quotes around keys and string values.
One non-obvious detail: JSON does not preserve object key order. While Python dictionaries since version 3.7 maintain insertion order, this behavior is not guaranteed in JSON itself. If order matters, use collections.OrderedDict or ensure data is processed sequentially.
To read JSON from a file, use json.load(). To write, use json.dump(). These functions accept file handles and automatically manage encoding and decoding.
Suppose you have a file called config.json:
{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp"
},
"debug": true
}
Reading it in Python:
import json
with open("config.json", "r") as f:
config = json.load(f)
print(config["database"]["host"]) # localhost
Writing updated data:
config["debug"] = False
with open("config.json", "w") as f:
json.dump(config, f, indent=2)
The indent argument formats the output for readability. Without it, the JSON appears as a single line.
I once debugged a production script that failed because a JSON file had trailing commas. The parser rejected it despite correct syntax. Trailing commas in arrays or objects are invalid in JSON. Removing them resolved the issue.
Understanding JSON in Python is essential for modern programming. It enables efficient data exchange, configuration management, and integration with web services. Mastering the json module reduces dependency on external tools and improves performance.