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

标签 python json

假设我有一个 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/

相关文章:

python - 如何使用 django-mailer 定时发送电子邮件

Python pytz : non-existent time gets AmbiguousTimeError, 不是 NonExistentTimeError

json - 快速迭代数组

ruby-on-rails - 如何在 Ruby on Rails 中使用 PostgreSQL JSON 数组查询 ActiveRecord::Relation

python - 按字符或空格 python 拆分行

python - 在 Python 中实现存储库模式?

python - 格式化字符串属性

javascript - 将特定的json元素转换为json中的数字

json - 将 json 数组解码为 swift 中的对象

json - 在Docker容器中设置环境变量