简体   繁体   中英

how to get a value from a json text Python

import requests
import json
r = requests.get("https://api.investing.com/api/search/?t=Equities&q=amd") # i get json text from this api
data = json.loads(r.text)
if data['articles'][0]['exchange'] == 'Sydney': # the error is here      KeyError: 'exchange'
   print('success')
else:
   print('fail')
 

if i want to get the url '/equities/segue-resources-ltd' by checking if the 'exchange' is 'Sydney' which is stored in this part of the json text, {"id":948190,"url":"/equities/segue-resources-ltd","description":"Segue Resources Ltd","symbol":"AMD","exchange":"Sydney","flag":"AU","type":"Equities"}

If i'm understanding this correctly, the exchange identifier only appears in part of the json response. So, in order to get your result using the same data variable in your question, we can do this:

result = [val["url"] for val in data["quotes"] if val["exchange"] == "Sydney"]

We are using a list comprehension here, where the loop is only going through data["quotes"] instead of the whole json response, and for each item in that json subset, we're returning the value for key == "url" where the exchange == "Sydney" . Running the line above should get you:

['/equities/segue-resources-ltd']

As expected. If you aren't comfortable with list comprehensions, the more conventional loop-version of it looks like:

result = []
for val in data["quotes"]:
    if val["exchange"] == "Sydney":
        result.append(val["url"])

print(result)
import requests
import json
r = requests.get("https://api.investing.com/api/search/?t=Equities&q=amd") # i get json text from this api
data = json.loads(r.text)
if data['articles'][0]['exchange'] == 'Sydney': # the error is here      KeyError: 'exchange'
   print('success')
else:
   print('fail')
 

if i want to get the url '/equities/segue-resources-ltd' by checking if the 'exchange' is 'Sydney' which is stored in this part of the json text, {"id":948190,"url":"/equities/segue-resources-ltd","description":"Segue Resources Ltd","symbol":"AMD","exchange":"Sydney","flag":"AU","type":"Equities"}

KeyError: 'exchange' means that the dictionary data['articles'][0] did not have a key 'exchange' .

Depending on your use case, you may want to iterate over the whole list of articles:

for article in data['articles']:
    if 'exchange' in article and article['exchange'] == 'Sydney':
        ...  # Your code here

If you only want to check the first article, then use data['articles'][0].get('exchange') . The dict.get() method will return None if the key is not present instead of throwing a KeyError .

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