2012-10-19 48 views
2

我试图解码与Python以下JSON文件:解码JSON与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"} 
] 
} 

使用:

json_data=open('sampleJSON') 
jdata = json.load(json_data) 
for key, value in jdata.iteritems(): 
    print "Key:" 
    print key 
    print "Value:" 
    print value 

,我有作为输出:

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'}] 

而且我希望能够打印键值和嵌套对象的值状态,coord,还有节点,“hid”,“id”,“ip”和“ts”的que键/值。

我如何在所有嵌套值中进行交互?

预先感谢您!

回答

7

您可以使用递归函数将其全部打印出来。这可以改善,但这里的理念是:

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 

输出

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 

否则,你可以只使用:

import pprint 
pprint.pprint(jdata) 
+0

太谢谢你了!它完全钉了它 – Tallis

-1

它看起来像您的JSON的顶级元素是一个包含词典列表的字典。如果你想保持这种结构,请尝试下面的代码。

from pprint import pprint 

json_data=open('sampleJSON') 
jdata = json.load(json_data) 
node = jdata['node'][0] 

for key, value in node.iteritems(): 
    pprint("Key:") 
    pprint(key) 
    pprint("Value:") 
    pprint(value) 
0

不知道更多关于你的具体使用情况,很难给出一般的答案,但是..

如果你有一个任意嵌套的结构,这是递归的一个很好的例子。

简单的示例代码:

def print_object(object, indent=0): 
    if type(object)==dict: 
     for key, value in object.iteritems(): 
      print " "*4*indent, "Key: ", key 
      print " "*4*indent, "Value: " 
      print_object(value, indent+1) 
    elif type(object)==list: 
     for value in object: 
      print_object(value,indent+1) 
    else: 
     print " "*4*indent, object 

你真的不想做严格的类型检查,但它适用于快速和肮脏的示例代码。

输出:

Key: node 
Value: 
     Key: status 
     Value: 
      Key: direction 
      Value: 
       N 
      Key: speed 
      Value: 
       90 
     Key: ip 
     Value: 
      172.20.0.1 
     Key: ts 
     Value: 
      12387 
     Key: coord 
     Value: 
      Key: lat 
      Value: 
       -9.8257 
      Key: lon 
      Value: 
       65.0880 
      Key: dist 
      Value: 
       12 
     Key: hid 
     Value: 
      213 
     Key: id 
     Value: 
      12387