【发布时间】:2019-12-29 20:35:57
【问题描述】:
我正在尝试编写一些代码来从 API 获取电子邮件(以及未来的其他内容)。但我收到“TypeError: list indices must be integers or slices, not str”,我不知道该怎么办。我一直在这里查看其他问题,但我仍然不明白。说到这个,我可能有点慢。 我也一直在看一些关于管的教程,并做了同样的事情,但仍然得到不同的错误。我运行 Python 3.5。
这是我的代码:
from urllib.request import urlopen
import json, re
# Opens the url for the API
url = 'https://jsonplaceholder.typicode.com/posts/1/comments'
r = urlopen(url)
# This should put the response from API in a Dict
result= r.read().decode('utf-8')
data = json.loads(result)
#This shuld get all the names from the the Dict
for name in data['name']: #TypeError here.
print(name)
我知道我可以正则表达式文本并获得我想要的结果。 代码:
from urllib.request import urlopen
import re
url = 'https://jsonplaceholder.typicode.com/posts/1/comments'
r = urlopen(url)
result = r.read().decode('utf-8')
f = re.findall('"email": "(\w+\S\w+)', result)
print(f)
但这似乎是错误的做法。 有人可以帮我理解我在这里做错了什么吗?
【问题讨论】:
-
解析完JSON后能否调试
data的类型?几乎可以肯定它是一个列表,在这种情况下,您应该遍历列表,然后从列表的每个元素中提取电子邮件(可能是一个字典?) -
for object in data: print(object['name'])试试这个 -
@IainShelvington 我在打印出
data的类型时得到<class 'list'>。所以列表是对的!
标签: python json python-3.x parsing