【问题标题】:Filter json value based on array根据数组过滤json值
【发布时间】:2021-04-08 15:04:48
【问题描述】:

我有一个像下面这样的 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=(',', ': '))
)

它不工作;你能帮忙吗

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

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

    [o for o in obj if int(o["id"]) not in remove_id]
    
    >> [{'ename': 'love', 'id': '3', 'url': 'love.com'}]
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 2018-11-06
      • 2015-10-13
      • 2017-03-13
      相关资源
      最近更新 更多