JSON (JavaScript Object Notation) is the de facto standard for exchanging data between a backend and a frontend, between two services, or simply for saving structured data to a file in a format any language can read back. Python's built-in json module converts cleanly between JSON text and native Python objects, so you rarely need a third-party library just to read or write it.
The mental model is simple: Python dictionaries and lists map almost directly onto JSON objects and arrays. The json module just handles the conversion in both directions.
Converting Python to JSON: json.dumps()
import json
user = {
"name": "Asha",
"age": 29,
"is_active": True,
"skills": ["Python", "SQL"]
}
json_string = json.dumps(user, indent=2)
print(json_string)
Output:
{
"name": "Asha",
"age": 29,
"is_active": true,
"skills": [
"Python",
"SQL"
]
}
Notice that Python's True became JSON's lowercase true — the json module automatically maps Python types to their JSON equivalents: dict → object, list/tuple → array, str → string, int/float → number, True/False → true/false, and None → null. The indent=2 argument is optional and just makes the output human-readable; leave it out for compact output.
Converting JSON Back to Python: json.loads()
raw = '{"name": "Asha", "age": 29}'
data = json.loads(raw)
print(data["name"], data["age"])
print(type(data))
Output:
Asha 29
<class 'dict'>
json.loads() parses a JSON string and returns a regular Python object — usually a dict or list — which you can then work with using normal dictionary operations.
Reading and Writing JSON Files
For files, use json.dump() and json.load() (no "s" — these work directly with a file object instead of a string), combined with the with statement so the file closes automatically:
# Writing to a file
with open("user.json", "w") as f:
json.dump(user, f, indent=2)
# Reading it back
with open("user.json", "r") as f:
loaded = json.load(f)
print(loaded["skills"])
Output:
['Python', 'SQL']
Common Mistake: Invalid JSON
JSON is stricter than Python syntax — it requires double quotes around strings (not single quotes), has no trailing commas, and has no support for Python-only values like NaN in strict mode. If json.loads() is given malformed JSON, it raises a json.JSONDecodeError, so it's worth wrapping untrusted input in a try/except block when parsing data from an external source like an API response.
