JSON Serialization
JSON (JavaScript Object Notation) is a lightweight, human-readable data format used for data interchange, especially between web servers and applications. Python's built-in json module handles converting Python objects into JSON strings and vice versa.
Mapping Python to JSON
| Python | JSON |
|---|---|
| Dict | Object |
| List, Tuple | Array |
| String | String |
| Int, Float | Number |
| True | true |
| False | false |
| None | null |
1. Encoding (Python to JSON String - .dumps())
Used to convert a Python dictionary or list into a JSON formatted string.
python import json
data = { "name": "Zoe", "age": 28, "is_active": True, "hobbies": ["reading", "coding"] }
The string representation of the data
json_string = json.dumps(data, indent=4) # indent=4 makes it readable print(json_string)
2. Decoding (JSON String to Python - .loads())
Converts a JSON formatted string back into a Python object (usually a dictionary).
python json_response = '{"id": 101, "status": "Success"}' python_data = json.loads(json_response)
print(python_data['status']) # Output: Success print(type(python_data)) # <class 'dict'>