4

我想用“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。我正在使用 Python 2.7

4

4 回答 4

10

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

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']
于 2013-09-16T15:05:32.480 回答
1

当您尝试在 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()(仅dict.items()在 python 3 中)

>>> 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'
于 2013-09-16T14:55:01.477 回答
1

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

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
于 2013-09-16T14:56:13.297 回答
0

试试这样:

output_json = json.load(open('root.json'))
if "children" in output_json:
  children = output_json["children"]
  if "children" in children:
    children1 = children["children"]
    if "children" in children1:
      children2 = children1["children"]
      if "name" in children2:
        name = children2["name"]
      if "Ids" in children2:
        ids = children2["Ids"]
      print name, ids
于 2013-09-16T14:55:19.900 回答