JSON is the standard format for exchanging data — an API response, a config file, data saved between program runs. Python's built-in json module handles converting between it and Python's own dicts and lists.
import json
user = {'name': 'Sam', 'age': 28, 'active': True}
json_string = json.dumps(user)
print(json_string)
# {"name": "Sam", "age": 28, "active": true}print(json.dumps(user, indent=2))json_string = '{"name": "Sam", "age": 28}'
user = json.loads(json_string)
print(user['name']) # Sam — a regular Python dict now# Writing
with open('user.json', 'w') as f:
json.dump(user, f, indent=2)
# Reading
with open('user.json') as f:
user = json.load(f)dump()/load() (no "s") work directly with an open file; dumps()/loads() (with an "s", for "string") work with a Python string already in memory.
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True / False | true / false |
| None | null |
try:
data = json.loads('{invalid json}')
except json.JSONDecodeError as e:
print(f'Invalid JSON: {e}')A one-way conversion for tuples
A tuple converts to a JSON array and comes back as a Python list, not a tuple — JSON has no tuple type of its own, so that distinction is lost in the round trip.