【发布时间】: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