【问题标题】:How to update json object with dictionary in python如何在python中用字典更新json对象
【发布时间】:2021-07-01 13:23:23
【问题描述】:

目标是更新包含特定键的 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 对象时,它应该从字典中选择键/值对,然后迭代到下一个键/值以获取下一个 json包含“corporateIdentificationNumber”的对象

代码:

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"}
]}

【问题讨论】:

  • 生成的 json 文件应该是什么样子?
  • @quamrana 嗨,感谢您抽出宝贵时间。我刚刚更新了我的问题,我希望结果看起来像
  • 那么,您是依靠dict 中的项目顺序(顺便说一句不好命名)来覆盖collection 列表中的值吗?
  • 是的,完全正确!不确定,如果这是正确的做法。我现在在深水里
  • JSON 对象是一个字典。

标签: python json python-3.x dictionary if-statement


【解决方案1】:

我认为您需要对项目使用迭代器:

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)

【讨论】:

  • 你是救生员。这是有效的,正是我所需要的。非常感谢!
【解决方案2】:
json_object["corporateIdentificationNumber"] = "updated value"
file = open("your_json_file.json", "w")
json.dump(json_object, file)
file.close()

【讨论】:

  • 只有代码的答案通常没有帮助。
  • 所需的信息被集成到代码中。 “更新值”和“your_json_file”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-24
  • 1970-01-01
  • 2020-03-14
  • 2014-10-29
  • 2015-06-24
相关资源
最近更新 更多