how to filter json array in python

Question:

That is the current json array I have.
I want get all json objects that type=1

before filter:

[ 
        {
            "type": 1
            "name" : "name 1",
        }, 
        {
            "type": 2
            "name" : "name 2",
        }, 
        {
            "type": 1
            "name" : "name 3"
        }, 
]

after filter:

[ 
        {
            "type": 1
            "name" : "name 1",
        }, 
        {
            "type": 1
            "name" : "name 3"
        }, 
]

please help.

Asked By: Majid Zandi

||

Answers:

Simply

print [obj for obj in dict if(obj['type'] == 1)] 

Example Link.

Answered By: Andy Ecca

The following snippet of code does exactly what you want, but BEWARE that your input (as written in the question) is not a valid json string, you can check here: http://jsonlint.com.

import json

input_json = """
[
    {
        "type": "1",
        "name": "name 1"
    },
    {
        "type": "2",
        "name": "name 2"
    },
    {
        "type": "1",
        "name": "name 3"
    }
]"""

# Transform json input to python objects
input_dict = json.loads(input_json)

# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if x['type'] == '1']

# Transform python object back into json
output_json = json.dumps(output_dict)

# Show json
print output_json
Answered By: Joaquin Sargiotto

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Documentation for filter

>>> obj=[
...     {
...         "type": 1,
...         "name": "name 1"
...     },
...     {
...         "type": 2,
...         "name": "name 2"
...     },
...     {
...         "type": 1,
...         "name": "name 3"
...     }
... ]
>>> filter(lambda x: x['type'] == 1, obj)
<filter object at 0x7fd98805ca00>
>>> list(filter(lambda x: x['type'] == 1, obj))
[{'type': 1, 'name': 'name 1'}, {'type': 1, 'name': 'name 3'}]
>>> list(filter(lambda x: x['type'] == 2, obj))
[{'type': 2, 'name': 'name 2'}]
Answered By: N N K Teja
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.