2024-11-19
import json
# 假设有一个字典
data = {
'name': 'John',
'age': 30,
'city': 'New York'
}
# 将字典转换为JSON字符串
json_string = json.dumps(data)
print(json_string) # 输出: {"name": "John", "age": 30, "city": "New York"}
=====================================
# 反过来,将JSON字符串转换为字典
json_string='{"name": "John", "age": 30, "city": "New York"}'
loaded_data = json.loads(json_string)
print(loaded_data) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
=====================================
# 将字典写入JSON文件
with open(json_file_path, 'w') as json_file:
json.dump(data, json_file)
=====================================
# 从JSON文件读取字典
with open(json_file_path, 'r') as json_file:
loaded_data_from_file = json.load(json_file)
print(loaded_data_from_file) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
=====================================
# 从JSON字符转列表
import json
# 假设json_data是一个JSON格式的字符串
json_data = '["apple", "banana", "cherry"]'
# 使用json模块将JSON字符串转换为Python列表
fruit_list = json.loads(json_data)
print(fruit_list) # 输出: ['apple', 'banana', 'cherry']
=====================================
# 列表转换为JSON
import json
# 假设有一个包含字典的列表
list_of_dicts = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 35, 'city': 'Los Angeles'}
]
# 将列表转换为JSON字符串
json_str = json.dumps(list_of_dicts)
print(json_str)