JSON (JavaScript Object Notation) is a common format for storing and exchanging data. Python's json module makes it easy to work with JSON.
What is JSON?
JSON looks similar to Python dictionaries and lists.
Example JSON data:
{
"name": "Alex",
"age": 25,
"hobbies": ["reading", "coding", "hiking"],
"is_student": false
}
Importing the json module
Always import json first:
import json
Converting Python to JSON (serializing)
Use json.dumps() for a string or json.dump() for a file.
To string:
data = {
"name": "Alex",
"age": 25,
"hobbies": ["reading", "coding"]
}
json_string = json.dumps(data)
print(json_string)
# {"name": "Alex", "age": 25, "hobbies": ["reading", "coding"]}
Pretty print with indentation:
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
To file:
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Converting JSON to Python (deserializing)
Use json.loads() for a string or json.load() for a file.
From string:
json_string = '{"name": "Sam", "age": 30}'
data = json.loads(json_string)
print(data["name"]) # Sam
From file:
with open("data.json", "r") as file:
data = json.load(file)
print(data["hobbies"]) # ['reading', 'coding']
Simple examples
Save a list of users to JSON:
users = [
{"name": "Alex", "age": 25},
{"name": "Sam", "age": 30}
]
with open("users.json", "w") as file:
json.dump(users, file, indent=4)
Read and print names:
with open("users.json", "r") as file:
users = json.load(file)
for user in users:
print(user["name"])
Important notes
- JSON keys must be strings.
- Supported types: dict, list, str, int, float, bool, None.
- Use
indentfor readable files. - Handle errors with try/except (e.g., invalid JSON or file not found).
Quick summary
- Import
jsonto work with JSON data. -
dumps()anddump()convert Python to JSON. -
loads()andload()convert JSON to Python. - Use indentation for human-readable output.
- JSON is perfect for configuration files and web APIs.
Practice saving and loading small data structures as JSON. It is essential for data exchange in Python programs.
Top comments (0)