要找到并替换JSON文件中出现的所有单词,并使用Python保存生成的JSON,可以按照以下步骤进行操作:
json
,可以使用json.load()
函数读取JSON文件并将其转换为Python对象。import json
with open('input.json', 'r') as file:
data = json.load(file)
replace()
来实现。def replace_words(obj, target_word, replacement):
if isinstance(obj, dict):
for key, value in obj.items():
if isinstance(value, (dict, list)):
replace_words(value, target_word, replacement)
elif isinstance(value, str):
obj[key] = value.replace(target_word, replacement)
elif isinstance(obj, list):
for i in range(len(obj)):
if isinstance(obj[i], (dict, list)):
replace_words(obj[i], target_word, replacement)
elif isinstance(obj[i], str):
obj[i] = obj[i].replace(target_word, replacement)
json.dump()
函数将Python对象转换为JSON字符串,并保存到新的JSON文件中。with open('output.json', 'w') as file:
json.dump(data, file)
完整的代码示例:
import json
def replace_words(obj, target_word, replacement):
if isinstance(obj, dict):
for key, value in obj.items():
if isinstance(value, (dict, list)):
replace_words(value, target_word, replacement)
elif isinstance(value, str):
obj[key] = value.replace(target_word, replacement)
elif isinstance(obj, list):
for i in range(len(obj)):
if isinstance(obj[i], (dict, list)):
replace_words(obj[i], target_word, replacement)
elif isinstance(obj[i], str):
obj[i] = obj[i].replace(target_word, replacement)
# 读取JSON文件
with open('input.json', 'r') as file:
data = json.load(file)
# 替换单词
replace_words(data, 'old_word', 'new_word')
# 转换为JSON并保存
with open('output.json', 'w') as file:
json.dump(data, file)
请注意,以上代码仅提供了一个基本的替换示例,实际应用中可能需要根据具体需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云