以下是一个遍历json数据并更新字典的示例代码:
import json
def update_dict(json_data, dictionary):
if isinstance(json_data, dict):
for key, value in json_data.items():
if key in dictionary:
if isinstance(value, dict) and isinstance(dictionary[key], dict):
update_dict(value, dictionary[key])
else:
dictionary[key] = value
elif isinstance(json_data, list):
for item in json_data:
if isinstance(item, dict):
update_dict(item, dictionary)
# 示例数据
json_str = '{"name": "John", "age": 30, "address": {"street": "123 Main St", "city": "New York"}}'
json_data = json.loads(json_str)
dictionary = {"name": "Jane", "age": None, "address": {"street": "", "city": ""}}
# 更新字典
update_dict(json_data, dictionary)
# 打印更新后的字典
print(dictionary)
运行以上代码,输出结果为:
{'name': 'John', 'age': 30, 'address': {'street': '123 Main St', 'city': 'New York'}}
在这个示例中,我们定义了一个名为update_dict
的函数,它接受两个参数:json_data
和dictionary
。函数首先检查json_data
是否为字典类型,如果是,则遍历其中的键值对。如果键存在于dictionary
中,那么会进一步检查值的类型。如果值是字典类型,那么会递归调用update_dict
函数,继续更新嵌套的字典。否则,直接将值更新到dictionary
中。
如果json_data
是列表类型,则会遍历其中的每个元素,并对其中的字典类型元素递归调用update_dict
函数。
在示例中,我们先将json字符串解析为python字典类型的json_data
,然后定义一个初始的dictionary
,其中的值将会被更新。最后,调用update_dict
函数来更新dictionary
。最终,打印出更新后的dictionary
。