【Python系列】深入解析 Python 中的 JSON 处理工具
warning:
这篇文章距离上次修改已过197天,其中的内容可能已经有所变动。
import json
# 解析JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
print(data) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
# 生成JSON字符串
data_to_json = {"name": "Jane", "age": 25, "city": "Los Angeles"}
json_str_2 = json.dumps(data_to_json)
print(json_str_2) # 输出: {"name": "Jane", "age": 25, "city": "Los Angeles"}
# 将JSON数据写入文件
json_file_path = 'user_info.json'
with open(json_file_path, 'w') as json_file:
json.dump(data_to_json, json_file)
# 从文件读取JSON数据
with open(json_file_path, 'r') as json_file:
data_from_file = json.load(json_file)
print(data_from_file) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
这段代码展示了如何在Python中使用json
模块来解析和生成JSON字符串,以及如何将JSON数据写入文件和从文件读取JSON数据。
评论已关闭