简体   繁体   English

Python http请求并遍历JSON的内容

[英]Python http request and loop over contents of JSON

I'm trying to learn Python and have following problem: I get an error while running this as it cannot see the 'name' attribute in data. 我正在尝试学习Python并遇到以下问题:运行此程序时出现错误,因为它无法在数据中看到'name'属性。 It works when I grab one by one items from JSON. 当我从JSON抓取一件物品时,它起作用。 However when I want to do it in a loop it fails. 但是,当我想循环执行时,它会失败。 I assume my error is wrong request. 我认为我的错误是错误的请求。 That it cannot read JSON correctly and see attributes. 无法正确读取JSON并查看属性。

import requests
import json

def main():

    req = requests.get('http://pokeapi.co/api/v2/pokemon/')

    print("HTTP Status Code: " + str(req.status_code))
    print(req.headers)
    json_obj = json.loads(req.content)

    for i in json_obj['name']:
        print(i)

if __name__ == '__main__':
    main()

You want to access the name attribute of the results attribute in your json_object like this: json_object这样在json_object访问results属性的name属性:

  for pokemon in json_obj['results']:
    print (pokemon['name'])

I was able to guess that you want to access the results keys because I have looked at the result of 我能够猜到您要访问results键,因为我查看了

json_obj.keys()

that is 那是

dict_keys(['count', 'previous', 'results', 'next'])

Because all pokemons are saved in a list which is under keyword results , so you firstly need to get that list and then iterate over it. 由于所有宠物小精灵都保存在关键字results之下的列表中,因此您首先需要获取该列表,然后对其进行迭代。

for result in json_obj['results']:
print(result['name'])

A couple things: as soon mentioned, iterating through json_obj['name'] doesn't really make sense - use json_obj['results'] instead. 有两件事:就像前面提到的,遍历json_obj['name']并没有多大意义-而是使用json_obj['results']

Also, you can use req.json() which is a method that comes with the requests library by default. 另外,您可以使用req.json() ,这是默认情况下requests库随附的方法。 That will turn the response into a dictionary which you can then iterate through as usual ( .iteritems() or .items() , depending if you're using Python 2 or 3). 这样会将响应转换成字典,然后您可以照常遍历字典( .iteritems().items() ,具体取决于您使用的是Python 2还是3)。

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

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