【问题标题】:Parsing Json in python 3, get email from API在 python 3 中解析 Json,从 API 获取电子邮件
【发布时间】: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


【解决方案1】:

data 是一个字典列表,这就是为什么你在迭代它时得到TypeError。
要走的路是这样的:

for item in data:  # item is {"name": "foo", "email": "foo@mail..."}
    print(item['name'])
    print(item['email'])

【讨论】:

  • 谢谢!你会说这比使用正则表达式更正确吗?
  • @Baconflip 绝对!由于 item 是字典(哈希映射),您可以通过键访问值。不需要正则表达式。事实上,那(使用正则表达式)将是违反直觉的方法。
【解决方案2】:

@PiAreSquared 的评论是正确的,这里稍微解释一下:

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) 

# your data is a list of elements
# and each element is a dict object, so you can loop over the data
# to get the dict element, and then access the keys and values as you wish
# see below for some example
for element in data: #TypeError here.
  name = element['name']
  email = element['email']

# if you want to get all names, you should do
names = [element['name'] for element in data]
# same to get all emails
emails = [email['email'] for email in data]

【讨论】:

  • 不错!谢谢你。这对我来说很有意义。
猜你喜欢
  • 2016-05-09
  • 2019-02-28
  • 2018-02-23
  • 2020-06-12
  • 2023-02-07
  • 2012-01-09
  • 2014-08-04
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多