Python 基于数组过滤json值
我有一个类似下面的jsonPython 基于数组过滤json值,python,arrays,json,Python,Arrays,Json,我有一个类似下面的json [ { "ename": "mark", "id": "1", "url": "Lennon.com" }, { "ename": "egg", "id": "2", &qu
[
{
"ename": "mark",
"id": "1",
"url": "Lennon.com"
},
{
"ename": "egg",
"id": "2",
"url": "egg.com"
},
{
"ename": "love",
"id": "3",
"url": "love.com"
}
]
我还有这样的数组[“1”,“2”]
我需要根据我的数组过滤掉数组值,所以最终的输出应该是
[
{
"ename": "love",
"id": "3",
"url": "love.com"
}
]
这是我现在拥有的代码:
obj = json.load(open("package.json"))
remove_id = ["1","2"]
# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for x in remove_id:
print x
for i in xrange(len(obj)):
if obj[i]["id"] == x:
obj.pop(i)
break
# Output the updated file with pretty JSON
open("updated-file-3.json", "w").write(
json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)
它不起作用;首先,它看起来像是
remove\u id
是int
的列表,但是id
键是str
,所以即使它匹配,也不会通过平等性测试。既然如此,就不需要修改原始对象,您可以使用列表创建副本
[o for o in obj if int(o["id"]) not in remove_id]
>> [{'ename': 'love', 'id': '3', 'url': 'love.com'}]