函数式编程
以下代码替换字典中的值(的子字符串)。它适用于嵌套的 json 结构并处理 json、列表和字符串类型。如果需要,您可以添加其他类型。def dict_replace_value(d, old, new): x = {} for k, v in d.items(): if isinstance(v, dict): v = dict_replace_value(v, old, new) elif isinstance(v, list): v = list_replace_value(v, old, new) elif isinstance(v, str): v = v.replace(old, new) x[k] = v return xdef list_replace_value(l, old, new): x = [] for e in l: if isinstance(e, list): e = list_replace_value(e, old, new) elif isinstance(e, dict): e = dict_replace_value(e, old, new) elif isinstance(e, str): e = e.replace(old, new) x.append(e) return x# See input and output belowb = dict_replace_value(a, 'string', 'something')输入:a = { 'key1': 'a string', 'key2': 'another string', 'key3': [ 'a string', 'another string', [1, 2, 3], { 'key1': 'a string', 'key2': 'another string' } ], 'key4': { 'key1': 'a string', 'key2': 'another string', 'key3': [ 'a string', 'another string', 500, 1000 ] }, 'key5': { 'key1': [ { 'key1': 'a string' } ] }}输出:{ "key1":"a something", "key2":"another something", "key3":[ "a something", "another something", [ 1, 2, 3 ], { "key1":"a something", "key2":"another something" } ], "key4":{ "key1":"a something", "key2":"another something", "key3":[ "a something", "another something", 500, 1000 ] }, "key5":{ "key1":[ { "key1":"a something" } ] }}