如何从JSON提取特定数据?

时间:2020-09-11 23:46:50

标签: python json

我似乎无法从我从链接中检索到的JSON中提取特定数据。 我编写了这段代码,似乎可以在x [print(x)上正常工作,正如从屏幕快照1中可以看到的那样。

但是,在执行最后两行时给出了错误。 [截屏2] 我从youtube的视频中看到了这一点,并亲自尝试了。

也许我在某个地方犯了一个错误,有人可以告诉我我在哪里做错了吗?

代码:

import json
import urllib.request

connection = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.json')
js = connection.read()
pj = json.loads(js)
x = json.dumps(pj,indent = 2)
#print(x)

for z in x:
    print(z["count"])

[{working fine upto print(x)] [截屏1]

[Showing "TypeError: string indices must be integers"] [截屏2]

1 个答案:

答案 0 :(得分:0)

众所周知,JSON是一种标准,它允许将数据从一种编程语言传递到另一种编程语言,以便他们可以将其消费到对象中

可以迭代的对象是pj变量

import json
import urllib.request

connection = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.json')
js = connection.read()
pj = json.loads(js)#stores dicts, python objects, iterate them
x = json.dumps(pj,indent = 2)#json here, remember is just a string, cant access them using x['key']


[print(z['count']) for z in pj['comments']]
[97, 97, 90, 90, 88, 87, 87, 80, 79, 79, 78, 76, 76, 72, ...]