I have a JSON file. I want to parse it and print the response in Dialogflow.
import json
some JSON:
x = '{ "first": {"Id": "1","Zone": "South", "Product": "toy"}, "second": {"Id": "2","Zone": "North", "Product": "softtoy"}, "third": {"Id": "1", "Zone": "East","Product": "bat"} }'
parse x:
y = json.loads(x)
Advertisement
Answer
Try this
import json # some JSON: x = '{"first": {"Id": "1","Zone": "South", "Product": "toy"}, "second": {"Id": "2","Zone": "North", "Product": "softtoy"}, "third": {"Id": "1", "Zone": "East","Product": "bat"}}' # parse x: y = json.loads(x) # Get the key `Zone` under `1` z = y['1']['Zone'] print(z) if z == 'South': print('Yes')
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
if y['1']['Zone'] == 'North': print('No') if y['1']['Id'] == 1: print('Yes')
Update : 2
I guess this is the one you are searching for
for i in y: print(i + " Id -> " + y[i]['Id']) print(i + " Zone -> " + y[i]['Zone'])
Output
second Id -> 2
second Zone -> North
first Id -> 1
first Zone -> South
Here is the working code : https://onlinegdb.com/rJ4Ui3m0E
Update : 3
for i in y: if y[i]['Id'] == "1": if y[i]['Zone'] == "East": print (y[i]['Product'])
Output
bat
Here is the working code : https://onlinegdb.com/rJ41KyER4