I have a JSON file. I want to parse it and print the response in Dialogflow.
JavaScript
x
2
1
import json
2
some JSON:
JavaScript
1
6
1
x = '{
2
"first": {"Id": "1","Zone": "South", "Product": "toy"},
3
"second": {"Id": "2","Zone": "North", "Product": "softtoy"},
4
"third": {"Id": "1", "Zone": "East","Product": "bat"}
5
}'
6
parse x:
JavaScript
1
2
1
y = json.loads(x)
2
Advertisement
Answer
Try this
JavaScript
1
16
16
1
import json
2
3
# some JSON:
4
x = '{"first": {"Id": "1","Zone": "South", "Product": "toy"}, "second": {"Id": "2","Zone": "North", "Product": "softtoy"}, "third": {"Id": "1", "Zone": "East","Product": "bat"}}'
5
6
# parse x:
7
y = json.loads(x)
8
9
# Get the key `Zone` under `1`
10
z = y['1']['Zone']
11
print(z)
12
13
14
if z == 'South':
15
print('Yes')
16
Output:
South
Yes
Update : 1
Your json is an object. It is not array. Check this https://stackoverflow.com/a/38561016/2086966
So, you does not have to iterate with a for-loop.
Just use as follows
JavaScript
1
5
1
if y['1']['Zone'] == 'North':
2
print('No')
3
if y['1']['Id'] == 1:
4
print('Yes')
5
Update : 2
I guess this is the one you are searching for
JavaScript
1
4
1
for i in y:
2
print(i + " Id -> " + y[i]['Id'])
3
print(i + " Zone -> " + y[i]['Zone'])
4
Output
second Id -> 2
second Zone -> North
first Id -> 1
first Zone -> South
Here is the working code : https://onlinegdb.com/rJ4Ui3m0E
Update : 3
JavaScript
1
5
1
for i in y:
2
if y[i]['Id'] == "1":
3
if y[i]['Zone'] == "East":
4
print (y[i]['Product'])
5
Output
bat
Here is the working code : https://onlinegdb.com/rJ41KyER4