That is the current json array I have. I want get all json objects that type=1
before filter:
JavaScript
x
15
15
1
[
2
{
3
"type": 1
4
"name" : "name 1",
5
},
6
{
7
"type": 2
8
"name" : "name 2",
9
},
10
{
11
"type": 1
12
"name" : "name 3"
13
},
14
]
15
after filter:
JavaScript
1
11
11
1
[
2
{
3
"type": 1
4
"name" : "name 1",
5
},
6
{
7
"type": 1
8
"name" : "name 3"
9
},
10
]
11
please help.
Advertisement
Answer
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.
JavaScript
1
30
30
1
import json
2
3
input_json = """
4
[
5
{
6
"type": "1",
7
"name": "name 1"
8
},
9
{
10
"type": "2",
11
"name": "name 2"
12
},
13
{
14
"type": "1",
15
"name": "name 3"
16
}
17
]"""
18
19
# Transform json input to python objects
20
input_dict = json.loads(input_json)
21
22
# Filter python objects with list comprehensions
23
output_dict = [x for x in input_dict if x['type'] == '1']
24
25
# Transform python object back into json
26
output_json = json.dumps(output_dict)
27
28
# Show json
29
print output_json
30