根据数组过滤json值

时间:2021-04-08 15:04:48

标签: python arrays json

我有一个像下面这样的 json

[
  {       
      "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=(',', ': '))
)

它不工作;你能帮忙吗

1 个答案:

答案 0 :(得分:2)

首先,看起来 remove_idlistint,但 id 键是 str 所以即使匹配它也赢了'没有通过平等测试。话虽如此,无需修改原始对象,您可以使用列表理解创建副本。

[o for o in obj if int(o["id"]) not in remove_id]

>> [{'ename': 'love', 'id': '3', 'url': 'love.com'}]
相关问题