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 |