2

我正在尝试使用 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'}]

我希望能够打印嵌套对象状态坐标的键和值,以及节点、“hid”、“id”、“ip”和“ts”的键/值。

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

先感谢您!

4

3 回答 3

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)
于 2012-10-19T02:11:00.653 回答
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
于 2012-10-19T02:14:22.427 回答
-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)
于 2012-10-19T02:06:15.897 回答