python读取json数据并替换字符串
要读取 JSON 数据并替换字符串,可以使用 Python 的 json 模块和字符串的 replace() 方法。
下面是一个示例代码:
import json
# 读取 JSON 数据
with open('data.json', 'r') as file:
data = json.load(file)
# 替换字符串
new_data = json.dumps(data).replace("old_string", "new_string")
# 输出替换后的 JSON 数据
print(new_data)
# 保存替换后的 JSON 数据到文件
with open('new_data.json', 'w') as file:
file.write(new_data)
在上面的代码中,假设 JSON 数据保存在文件 data.json 中。首先使用 json.load() 方法将 JSON 数据加载为 Python 对象 data。然后,使用 json.dumps() 方法将 Python 对象转换为 JSON 字符串,并使用 replace() 方法替换字符串。最后,通过 print() 函数输出替换后的 JSON 字符串,并使用 write() 方法将其保存到新的 JSON 文件 new_data.json 中。
请注意,这只是一个示例代码,你需要根据实际情况修改文件名和替换的字符串
原文地址: https://www.cveoy.top/t/topic/iMRf 著作权归作者所有。请勿转载和采集!