【问题标题】:How to extract specific data from JSON?如何从 JSON 中提取特定数据?
【发布时间】:2020-09-11 23:46:50
【问题描述】:

我似乎无法从我从链接中检索到的 JSON 中提取特定数据。 我编写了这段代码,从截图 1 中可以看出,在 x [print(x) 之前,我似乎可以正常工作。

但是,它在执行最后两行时出错。 [截图 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"])

[] [screenshot-1]

[] [Screenshot-2]

【问题讨论】:

标签: python json


【解决方案1】:

众所周知,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, ...]

【讨论】:

  • 明白了,谢谢大哥! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2020-10-02
  • 2015-02-18
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多