Sum JSON对象并在Python中获取JSON文件

时间:2013-10-18 23:07:28

标签: python json sum

我有一个包含许多对象的JSON文件。我想过滤它以丢弃没有名为'id'的特定字段的所有对象。我开发了一段代码,但它不起作用:

import json
b=open("all.json","r")
sytems_objs=json.loads(b.read())
flag=0
for i in range(len(sytems_objs)):
    if sytems_objs[i]["id"]<>None:
        if flag==0:
            total=sytems_objs[i]
            flag=1
        else:
            total=total+sytems_objs[i]

file1=open("filtered.json","w+")
json.dump(total, file1)

c=open("filtered.json","r")
sytems_objs2=json.loads(b.read())

我收到错误:ValueError: No JSON object could be decoded

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我假设system_objs最初是一个对象数组

system_objs = json.loads(b.read())

# create a list that only have dicts with the property 'id'
# just read the comment to also include if id is not null
system_objs = [o for o in system_objs if 'id' in o and o['id'] is not None]

# how many dicts have 'id' with it
print len(system_objs)

# write the system objs to a json file
with open('filtered.json', 'w') as f:
    f.write(json.dumps(system_objs))