import json
# 示例JSON字符串
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'
# 将JSON字符串解析为Python字典
parsed_data = json.loads(json_string)
print("解析后的Python字典:", parsed_data)
# 修改字典中的数据
parsed_data['age'] = 26
# 将Python字典转换回JSON字符串
new_json_string = json.dumps(parsed_data)
print("转换后的JSON字符串:", new_json_string)
# 写入JSON数据到文件
with open('data.json', 'w') as json_file:
json.dump(parsed_data, json_file)
# 从文件读取JSON数据
with open('data.json', 'r') as json_file:
data_from_file = json.load(json_file)
print("从文件读取的JSON数据:", data_from_file)
import json
导入Python的内置JSON处理模块。json.loads()
方法将JSON格式的字符串解析为Python字典。json.dumps()
方法将Python字典转换回JSON格式的字符串。json.dump()
方法将Python字典写入JSON文件。json.load()
方法从JSON文件中读取数据并解析为Python字典。通过这些步骤,你可以轻松地在Python中处理JSON数据。
上一篇:python 遍历dict
下一篇:python语言程序设计基础
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站