gpt4 book ai didi

Python 替换未知结构 JSON 文件中的值

转载 作者:行者123 更新时间:2023-11-28 20:33:26 24 4
gpt4 key购买 nike

假设我有一个 JSON 文件,其结构未知或可能随时间变化 - 我想用我在 Python 中选择的字符串替换“REPLACE_ME”的所有值。

我发现的一切都假设我知道结构。例如,我可以使用 json.load 读取 JSON 并遍历字典进行替换,然后将其写回。这假设我知道 key 名称、结构等。

如何用其他内容替换 JSON 文件中的所有给定字符串值?

最佳答案

此函数递归地用值 new 替换所有等于值 original 的字符串。

此函数适用于 python 结构 - 但当然您可以在 json 文件上使用它 - 通过使用 json.load

它不会替换字典中的键 - 只是替换值。

def nested_replace( structure, original, new ):
if type(structure) == list:
return [nested_replace( item, original, new) for item in structure]

if type(structure) == dict:
return {key : nested_replace(value, original, new)
for key, value in structure.items() }

if structure == original:
return new
else:
return structure

d = [ 'replace', {'key1': 'replace', 'key2': ['replace', 'don\'t replace'] } ]
new_d = nested_replace(d, 'replace', 'now replaced')
print(new_d)
['now replaced', {'key1': 'now replaced', 'key2': ['now replaced', "don't replace"]}]

关于Python 替换未知结构 JSON 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50631393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com