0

我有一个包含许多对象的 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

我究竟做错了什么?

4

1 回答 1

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))
于 2013-10-18T23:24:08.763 回答