目标是更新包含特定键的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"}
]}
我认为您需要使用迭代器来处理以下项:
相关问题 更多 >
编程相关推荐