简体   繁体   中英

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

You should be looping over info["comments"] which is a list. You can also use the sum function to total the values

b = sum(float(i["count"]) for i in info["comments"])

This:

 for i in info: 

iterates over the dict, which yields keys, which are strings. Access info directly instead.

This is python list comprehension:

tt = sum([float(row['count']) for row in info['comments']])
print tt

or this is "for" loops

tt = [] 
for row in info['comments']:
    tt.append(float(row['count']))

b = sum(tt)
print b

List comprehension is usually faster...

Your code:

    data= '''
[{
  "note":" sample data ",
  "comments":
  [
    {
      "School":"UCLA",
      "count":97
    },
    {
      "School":"MIT",
      "count":97
    },
    {
      "School":"Rutgers",
      "count":90
    }
  ]
}]'''

Use the above as data and your code should work... You are missing opening '[' and closing ']'...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM