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
Traceback (most recent call last):
File "testty.py", line 28, in <module>
number= i["comments"][0]["count"]
TypeError: string indices must be integers
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