d_luffy_de
d_luffy_de

Reputation: 967

Filter json value based on array

I have a json like below

[
  {       
      "ename": "mark",
      "id": "1",
      "url": "Lennon.com"
  },
  {
      "ename": "egg",
      "id": "2",
      "url": "egg.com"
  },
  {
      "ename": "love",
      "id": "3",
      "url": "love.com"
  }
]

I also have a array like this ["1", "2"]

I need to filter out the array values based on my array, so the final out put should be

[
  {
      "ename": "love",
      "id": "3",
      "url": "love.com"
  }
]

This is the code I have now:

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

Its not working; Can you please help

Upvotes: 0

Views: 48

Answers (1)

gold_cy
gold_cy

Reputation: 14216

First off, it looks like remove_id is a list of int, but the id key is a str so even if it matches it won't pass the equality test. With that being said, there is no need to modify the original object, you can create a copy using a list-comprehension.

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

>> [{'ename': 'love', 'id': '3', 'url': 'love.com'}]

Upvotes: 2

Related Questions