简体   繁体   中英

Python JSON Element Access with 2 responses

I can't find the right search term to come up with an answer to this but I know it's a noob question. I'm accessing an API which returns either:

{  
   "Items":[  
      {  
         "Id":"12",
         "Type":"Address",
         "Highlight":"564754165545",
      }
   ]
}

or sometimes:

{  
   "Items":[  
      {  
         "Id":"12",
         "Type":"BuildingNumber",
         "Highlight":"145454479854",
      },
      {  
         "Id":"12",
         "Type":"Address",
         "Highlight":"564754165545",
      }
   ]
}

I need to get the "highlight" element data but only when type is address from a reply.

Thanks for your help and sorry I couldn't work out the name of the multiple rows to find this for myself.

Items is a list of dicts. According to your example, sometimes the list contains one item, and other times it contains two items.

for item in foo['Items']:
    if item['Type'] == 'Address':
        print (item['Highlight'])

Use following code

new_items = [ j for j in JSON['Items'] if j.get('Type') == 'Address' ] 
JSON = {'Items' : new_items }

for only heighlight data

new_items = [ j.get('heighlight') for j in JSON['Items'] if j.get('Type') == 'Address' ] 

获取具有“ Address Type的高亮对象的列表

[highlight for highlight in respose['Items'] if highlight['Type'] == 'Address']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM