使用Python解码JSON并存储嵌套对象

时间:2012-10-19 01:55:23

标签: python json

我正在尝试使用Python解码以下JSON文件:

{"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 的键和值,以及节点的que键/值,“hid”,“id”,“ip”和“ts”。

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

提前谢谢!

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分:-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)
相关问题