Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...