Decoding JSON with Python and storing nested object
json, python
Solution
You can use a recursive function to print it all out. This could be improved, but here is the idea:
import json
json_data = open('data.json')
jdata = json.load(json_data)
def printKeyVals(data, indent=0):
if isinstance(data, list):
print
for item in data:
printKeyVals(item, indent+1)
elif isinstance(data, dict):
print
for k, v in data.iteritems():
print " " * indent, k + ":",
printKeyVals(v, indent + 1)
else:
print data
OUTPUT
node:
status:
direction: N
speed: 90
ip: 172.20.0.1
ts: 12387
coord:
lat: -9.8257
lon: 65.0880
dist: 12
hid: 213
id: 12387
Otherwise, you could just use:
import pprint
pprint.pprint(jdata)
Problem
I am trying to decode the following JSON file with Python: ``` {"node":[ { "id":"12387", "ip":"172.20.0.1", "hid":"213", "coord":{"dist":"12","lat":"-9.8257","lon":"65.0880"}, "status":{"speed":"90","direction":"N"}, "ts":"12387"} ] } ``` By using: ``` json_data=open('sampleJSON') jdata = json.load(json_data) for key, value in jdata.iteritems(): print "Key:" print key print "Value:" print value ``` and i have as output: ``` Key: node Value: [{u'status': {u'direction': u'N', u'speed': u'90'}, u'ip': u'172.20.0.1', u'ts': u'12387', u'coord': {u'lat': u'-9.8257', u'lon': u'65.0880', u'dist': u'12'}, u'hid': u'213', u'id': u'12387'}] ``` And i want to be able to print the key's and values of the nested objects status, coord, and also que key/values of node, "hid", "id", "ip" and "ts". How can i interate throughout all the nested values? Thank you in advance!