How can we use the “import json” command in Python?
In Python, you can import the json module using the “import json” statement and then use the functions and classes within the module to handle JSON data.
Here are some examples of common functions and classes in the json module.
- Convert JSON string into a Python object.
import json
# JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串转换为Python对象
python_obj = json.loads(json_str)
print(python_obj) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
- Convert Python objects to JSON strings.
import json
# Python对象
python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python对象转换为JSON字符串
json_str = json.dumps(python_obj)
print(json_str) # 输出: {"name": "John", "age": 30, "city": "New York"}
- Read the JSON file and parse it into a Python object.
import json
# 读取JSON文件
with open('data.json') as json_file:
json_str = json_file.read()
# 解析JSON字符串为Python对象
python_obj = json.loads(json_str)
print(python_obj)
- Write Python object to a JSON file.
import json
# Python对象
python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python对象转换为JSON字符串
json_str = json.dumps(python_obj)
# 将JSON字符串写入文件
with open('data.json', 'w') as json_file:
json_file.write(json_str)
These are just a few basic usage examples of the json module. The json module also provides other functions and classes to handle more complex JSON data. You can refer to the official documentation for more information: json – Python Standard Library Documentation.