对JSON对象求和并获取Python中的JSON文件

对JSON对象求和并获取Python中的JSON文件,python,json,sum,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=

我有一个包含许多对象的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())
导入json
b=open(“all.json”、“r”)
sytems_objs=json.loads(b.read())
标志=0
对于范围内的i(len(sytems_objs)):
如果系统[i][“id”]无:
如果标志==0:
总计=sytems_objs[i]
标志=1
其他:
总计=总计+系统对象[i]
file1=open(“filtered.json”,“w+”)
json.dump(总计,文件1)
c=open(“filtered.json”、“r”)
sytems_objs2=json.load(b.read())
我得到一个错误:
ValueError:无法解码任何JSON对象


我做错了什么?

我假设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))

您是否打算在追加模式下打开
filtered.json
?通常情况下,您不能这样做,并且希望它是您得到的有效json。您想要:或
echo…|之类的东西吗/jq“map(select(.id))”
?我想要的是创建另一个JSON文件,其中仅包含项
id
不同于null的eMelent。因此,在您的示例中,它将是
[{“id”:123,“a”:2}]
,因为它是唯一具有
id
元素的元素,您可以使用
json.load(b)
json.dump(system_objs,f)
。同样有效的
id
s可能有,也就是说,您可以简化测试:
L=[o for o in L if o.get('id')]