简体   繁体   English

从JSON文件获取值

[英]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. 你应该循环遍历info["comments"]这是一个列表。 You can also use the sum function to total the values 您还可以使用sum函数来累计值

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. 迭代dict,产生键,这是键。 Access info directly instead. 直接访问info

This is python list comprehension: 这是python列表理解:

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

or this is "for" loops 或者这是“for”循环

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. 顶级JSON对象不是数组,因此不应对其进行迭代。 The array is in info["comments"] , so do 数组在info["comments"] ,所以也是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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