import json
32 JSON
Basic Operations in the json
Module
- Serialization: Converting a Python object (e.g., dictionary, list, etc.) into a JSON string.
- Deserialization: Converting a JSON string into a Python object (e.g., dictionary, list, etc.).
32.1 Serialization (Convert Python -> JSON)
32.1.1 json.dumps()
This function is used to convert (serialize) a Python object into a JSON-formatted string.
import json
# Python dictionary
= {
person "name": "Alice",
"age": 30,
"city": "New York",
"is_employee": True
}
# Convert Python object to JSON string
= json.dumps(person)
json_string print(json_string)
{"name": "Alice", "age": 30, "city": "New York", "is_employee": true}
dumps()
converts the Python object to a JSON string.- Python data types like
dict
,list
,int
,str
, andbool
are automatically converted to corresponding JSON types.True
becomestrue
(in JSON format).- Strings are enclosed in double quotes in JSON.
To save the JSON string to a file, use the json.dump()
function. This function writes the JSON representation directly to a file.
with open('person.json', 'w') as file:
file) json.dump(person,
32.2 Deserialization (JSON -> Python Object)
32.2.1 json.loads()
This function is used to parse (deserialize) a JSON-formatted string into a Python object.
import json
# JSON string
= '{"name": "Alice", "age": 30, "city": "New York", "is_employee": true}'
json_string
# Convert JSON string to Python object (dictionary)
= json.loads(json_string)
person_dict print(person_dict)
{'name': 'Alice', 'age': 30, 'city': 'New York', 'is_employee': True}
loads()
converts a JSON string to a corresponding Python object.true
in JSON becomesTrue
in Python.- JSON strings are converted to Python dictionaries.
To read JSON data from a file and convert it into a Python object, use the json.load()
function.
with open('person.json', 'r') as file:
= json.load(file)
person_dict
print(person_dict)
32.2.2 Summary:
json.dumps()
converts a Python object to a JSON string.json.loads()
converts a JSON string back to a Python object.json.dump()
writes a Python object as JSON data to a file.json.load()
reads JSON data from a file and converts it back to a Python object.
The json
module makes it easy to work with JSON data, whether you are reading from or writing to files, or converting between Python objects and JSON strings.