How to filter json array in python

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

before the 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.

+3


source to share


2 answers


The following code snippet does exactly what you want, but EXPECT 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

      

+16


source


Just

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

      



Example Link .

+2


source







All Articles