如何在python中使用字典更新json对象

2024-10-08 22:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是更新包含特定键的json对象

json文件如下所示:

{
 "collection": [
{"name": "name1", "phone": "10203040"}, 
{"name": "name2", "phone": "20304050", "corporateIdentificationNumber": "1234"}, 
{"name": "name3", "phone": "30405060", "corporateIdentificationNumber": "5678"}
]}

如果json对象包含键“corporateIdentificationNumber”,则迭代一个命令并从字典中更新“name”和“corporateIdentificationNumber”。字典如下所示:

dict = {"westbuilt": "4232", "Northbound": "5556"}

换句话说,这意味着我需要用字典更新json对象,每当我更新json对象时,它都应该从字典中选择键/值对,然后迭代到下一个包含“corporateIdentificationNumber”的json对象的下一个键/值

代码:

r = requests.get(url="*URL*")
file = r.json()

for i in file['collection']:
    if 'corporateIdentificationNumber' in i:
        --- select next iterated key/value from dict---
        --- update json object ---

结果应该如下所示:

   {
 "collection": [
{"name": "name1", "phone": "10203040"}, 
{"name": "westbuilt", "phone": "20304050", "corporateIdentificationNumber": "4232"}, 
{"name": "Northbound", "phone": "30405060", "corporateIdentificationNumber": "5556"}
]}

Tags: 文件对象nameinjson目标字典phone
2条回答
json_object["corporateIdentificationNumber"] = "updated value"
file = open("your_json_file.json", "w")
json.dump(json_object, file)
file.close()

我认为您需要使用迭代器来处理以下项:

updates = {"westbuilt": "4232", "Northbound": "5556"}

r = requests.get(url="*URL*")
file = r.json()

items = iter(updates.items())
try:
    for i in file['collection']:
        if 'corporateIdentificationNumber' in i:
            d = next(items)
            i['name'] = d[0]
            i["corporateIdentificationNumber"] = d[1]
except StopIteration:
    pass

print(file)

相关问题 更多 >

    热门问题