从JSON中不同嵌套级别提取对象名称 [英] Extract the object names from different nesting levels in JSON

查看:75
本文介绍了从JSON中不同嵌套级别提取对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从以前的问题中获取解决方案,以运行 JSON 这是我的json,我想提取SUB,SUBSUB和NAME,并且在使用准for-chain时,我无法让自己回到层次结构中来获得SUBSUB2 ...有人可以以某种方式让我走上正确的轨道吗?

I've been trying to get the solution from my former question to running here, but unfortunately without success. I'm trying right now to change the code to deliver me in result not the Ids, but the "name" values itself. JSON this is my json, I want to extract the SUB, SUBSUB and NAME and when using a quasi for-chain, I cound not get back in hierarchy to get the SUBSUB2... Could anyone please put me somehow on the right track?

前一个问题的解决方案代码:

The solution code from the former question:

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

我真正想要实现的是简单列表,例如SUB1,SUBSUB1,NAME1,NAME2,SUBSUB2等...

What I exactly want to achieve is simple list as SUB1, SUBSUB1, NAME1, NAME2, SUBSUB2, etc...

推荐答案

假设x是您的JSON,

def trav(node, acc = []):
    acc += [node['name']]
    if 'children' in node:
        for child in node['children']:
            trav(child, acc)

acc = []
trav(x, acc)
print acc

输出:

['MAIN', 'SUB1', 'SUBSUB1', 'NAME1', 'NAME2', 'SUBSUB2', 'SUBSUB3']

另一个更紧凑的解决方案:

Another, more compact solution:

from itertools import chain         

def trav(node):
    if 'children' in node:
        return [node['name']] + list(chain.from_iterable([trav(child) for child in node['children']]))
    else:
        return [node['name']]

print trav(x)

这篇关于从JSON中不同嵌套级别提取对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆