Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

python - How to extract specific data from JSON?

I can't seem to extract specific data from JSON which I retrieved from a link. I wrote this code and seems to work fine up to x [print(x) that is] as you can see from the screenshot-1.

But, it's giving errors while executing the last 2 lines. [Screenshot-2] I saw this from a video on youtube and tried it on my own.

Maybe I am making a mistake somewhere, Can anybody please tell me where am I doing wrong?

Code:

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)] [screenshot-1]

[Showing "TypeError: string indices must be integers"] [Screenshot-2]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you well know JSON is a standard that allows to pass data from one programming language to another so they could consume them into their objects

an object that can be iterated is pj variable

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, ...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...