What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format used for storing and exchanging data between a server and a client (like a website or app).
It is language-independent and easy to read/write for both humans and machines.
Why Use JSON in Python?:
- Exchange data between Python and web APIs.
- Store structured data (e.g., settings, configurations).
- Easily serialize Python objects.
Python & JSON Integration
Python comes with a built-in module called json to work with JSON data.
Converting Between JSON and Python
| JSON |
Python Equivalent |
Object |
dict |
Array |
list |
String |
str |
Number |
int or float |
true / false |
True / False |
null |
None |
Convert Python → JSON (json.dumps( ))
import json
data = {"name": "Alice", "age": 25, "is_student": False}
json_string = json.dumps(data)
print(json_string)
# Output: {"name": "Alice", "age": 25, "is_student": false}
You can also pretty print it :
print(json.dumps(data, indent=4))
Convert JSON → Python (json.loads( ))
json_data = '{"name": "Alice", "age": 25}'
python_dict = json.loads(json_data)
print(python_dict["name"]) # Output: Alice
Working with JSON Files
Write to a JSON file
data = {"name": "Bob", "age": 30}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Read from a JSON file
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
Advanced Options in json Module
| Function |
Use Case |
json.dumps( ) |
Convert Python → JSON string |
json.dump( ) |
Write Python object to file (as JSON) |
json.loads( ) |
Parse JSON string → Python object |
json.load( ) |
Read JSON from file → Python object |
sort_keys=True |
Sort keys in output JSON |
indent=4 |
Pretty-print JSON |
Example Use Case
import json
person = {"name": "John", "skills": ["Python", "Django"], "active": True}
# Convert and save
with open("person.json", "w") as f:
json.dump(person, f, indent=2)
# Load and access
with open("person.json") as f:
data = json.load(f)
print(data["skills"][0]) # Output: Python
Summary
- Use json module to work with JSON data in Python.
- Convert between JSON strings and Python objects.
- Easily read/write JSON files for APIs and data storage.