sooraj sooraj - 6 months ago 15
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 ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"Rutgers",
"count":90
}
]
}'''

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


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

Traceback (most recent call last):
File "testty.py", 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.

Thanks

Answer

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