Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to filter json array in python

Tags:

python

json

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.

like image 299
Majid Zandi Avatar asked Nov 28 '14 13:11

Majid Zandi


People also ask

How do I query JSON data in Python?

Example-1: Search key in simple JSON data Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, 'in' operator is used to search the key.

How do I filter nested JSON data in Python?

As the loaded json data is just nested lists and dicts, you can use the ordinary list/dict operations; in particular, list comprehension is useful. Show activity on this post. import json # Loding the data pathToFile = "bb. json" with open(pathToFile, 'r') as file: content = file.

Can I filter JSON?

The filters key allows you to filter the query results for records matching specific values. You can string together multiple filters by constructing JSON arrays called filters, separating each filter by a comma, and joining them by the AND or the OR operator.


2 Answers

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 
like image 105
Joaquin Sargiotto Avatar answered Oct 02 '22 15:10

Joaquin Sargiotto


Simply

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

Example Link.

like image 35
Andy Ecca Avatar answered Oct 02 '22 15:10

Andy Ecca