简体   繁体   English

如何从 json 文本 Python 中获取值

[英]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"}如果我想通过检查 'exchange' 是否为存储在 json 文本的这一部分中的 'Sydney' 来获取 url '/equities/segue-resources-ltd',{"id":948190,"url": "/equities/segue-resources-ltd","description":"Segue Resources Ltd","symbol":"AMD","exchange":"Sydney","flag":"AU","type":"股票"}

If i'm understanding this correctly, the exchange identifier only appears in part of the json response.如果我理解正确, exchange标识符仅出现在 json 响应的一部分中。 So, in order to get your result using the same data variable in your question, we can do this:因此,为了在您的问题中使用相同的data变量获得结果,我们可以这样做:

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" .我们在这里使用列表理解,其中循环仅通过data["quotes"]而不是整个 json 响应,对于 json 子集中的每个项目,我们返回key == "url"的值其中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"}如果我想通过检查存储在 json 文本的这一部分中的“交易所”是否为“悉尼”来获得 url '/equities/segue-resources-ltd',{"id":948190,"url:" "/equities/segue-resources-ltd","description":"Segue Resources Ltd","symbol":"AMD","exchange":"Sydney","flag":"AU","type":"股票”}

KeyError: 'exchange' means that the dictionary data['articles'][0] did not have a key 'exchange' . KeyError: 'exchange'表示字典data['articles'][0]没有键'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') .如果您只想查看第一篇文章,请使用data['articles'][0].get('exchange') The dict.get() method will return None if the key is not present instead of throwing a KeyError .如果键不存在, dict.get()方法将返回None而不是抛出KeyError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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