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.
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.
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.
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.
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
Simply
print [obj for obj in dict if(obj['type'] == 1)]
Example Link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With