Index
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data.
✅ It’s like a Python dictionary, but in string form.
Python and JSON
Python has a built-in module called json that allows you to work with JSON data.
➤ Import the module:
import json
✅ 1. Convert Python to JSON (Serialize)
➤ json.dumps()
Converts Python objects (like dict, list) → JSON string.
import json
data = {
"name": "Alice",
"age": 25,
"is_student": False
}
json_data = json.dumps(data)
print(json_data)
🖨 Output:
{"name": "Alice", "age": 25, "is_student": false}
✅ 2. Convert JSON to Python (Deserialize)
➤ json.loads()
Converts JSON string → Python object.
import json
json_string = '{"name": "Bob", "age": 30, "is_student": true}'
data = json.loads(json_string)
print(data["name"]) # Output: Bob
✅ 3. Read from a JSON file
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
✅ 4. Write to a JSON file
import json
data = {
"name": "Charlie",
"city": "New York"
}
with open('data.json', 'w') as file:
json.dump(data, file)
🔁 Summary Table
| Function | Purpose |
|---|---|
json.dumps() | Python → JSON string |
json.loads() | JSON string → Python object |
json.dump() | Write JSON to a file |
json.load() | Read JSON from a file |