使用JSON库从Python的嵌套JSON中获取元素

2024-09-30 01:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用“BoxDet”名称列出“BoxDet”中的所有元素。目的是这样列出来:BoxDet:ABC。。。

我的JSON的一小部分:

{
   "id":1,
   "name":"BoxH",
   "readOnly":true,
   "children":[
      {
         "id":100,
         "name":"Box1",
         "readOnly":true,
         "children":[
            {
               "id":1003,
               "name":"Box2",
               "children":[
                  {
                     "id":1019,
                     "name":"BoxDet",
                     "Ids":[
                        "ABC",
                        "ABC2",
                        "DEF2",
                        "DEFHD",
                        "LKK"
                        ]
                    }
                ]
            }
        ]
    }
    ]
}

我的问题刚刚开始,我只是不能像第一个{}那样深入。 我的代码。。。

output_json = json.load(open('root.json'))
for first in output_json:
    print first
    for second in first:
        print second

。。。给我这样的回复:

readOnly
r
e
a
d
O
n
l
y
children
c
h
i
l
d
r
e
n

。。。等等。我甚至不能更深入地了解Box1,更不用说Box2了。我正在使用Python2.7


Tags: nameinidjsontrueforoutputfirst
3条回答

为此,需要一个树搜索算法:

def locateByName(e,name):
    if e.get('name',None) == name:
        return e

    for child in e.get('children',[]):
        result = locateByName(child,name)
        if result is not None:
            return result

    return None

现在可以使用此递归函数来定位所需的元素:

node = locateByName(output_json, 'BoxDet')
print node['name'],node['Ids']

当你试图在一个dict上使用for循环时,没有任何特别的考虑,你只得到dict中的键

>>> my_dict = {'foo': 'bar', 'baz':'quux'}
>>> list(my_dict)
['foo', 'baz']
>>> for x in my_dict:
...     print repr(x)    
'foo'
'baz'

最常见的做法是使用dict.iteritems()(在python 3中仅使用dict.items()

>>> for x in my_dict.iteritems():
...     print repr(x)
('foo', 'bar')
('baz', 'quux')

或者您可以自己获取密钥的值:

>>> for x in my_dict:
...     print repr(x), repr(my_dict[x])    
'foo' 'bar'
'baz' 'quux'

如果要遍历实体的子级,可以执行以下操作:

for children in output_json["children"]:
    #Going down to ID: 100 level
    for grandchildren in children["children"]:
        #Going down to ID: 1003 level
        for grandgrandchildren in grandchildren["children"]:
            #Going down to ID: 1019 level
            if grandgrandchildren["name"] == "BoxDet":
                return "BoxDet" + " ".join(grandgrandchildren["Ids"])

json模块中涉及的数据结构并不像经典字典那样工作,在经典字典中,您可以通过键访问值:

my_dict[key] = value

相关问题 更多 >

    热门问题