sooraj sooraj - 1 year ago 87
JSON Question

Getting values from JSON file

I am trying to get the values from count and add them to find the total sum.
The code I have written is:

import json
data= '''
"note":" sample data ",

info = json.loads (data)
print json.dumps(info, indent=4)
for i in info:
number= i["comments"][0]["count"]
for n in number:
print b

When I execute this, the output I am getting is:

Traceback (most recent call last):
File "", line 28, in <module>
number= i["comments"][0]["count"]
TypeError: string indices must be integers

Can some one please tell me what I am doing wrong and how to fix it.


Answer Source

The top-level JSON object is not an array, so you shouldn't iterate over it. The array is in info["comments"], so do

for i in info["comments"]:
    a = float(i["count"])
    b += a
print b