编程语言
首页 > 编程语言> > 以点表示法返回python嵌套dict / json文档中所有变量名称的列表

以点表示法返回python嵌套dict / json文档中所有变量名称的列表

作者:互联网

我正在寻找一个以JSON格式格式在python任意嵌套的dict /数组上运行的函数,并返回一个字符串列表,将其包含的所有变量名称键入到无限深度.所以,如果对象是……

x = {
    'a': 'meow',
    'b': {
        'c': 'asd'
    },
    'd': [
        {
            "e": "stuff",
            "f": 1
        },
        {
            "e": "more stuff",
            "f": 2
        }
    ]
}

mylist = f(x)会返回…

>>> mylist
['a', 'b', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f']

解决方法:

def dot_notation(obj, prefix=''):
     if isinstance(obj, dict):
         if prefix: prefix += '.'
         for k, v in obj.items():
             for res in dot_notation(v, prefix+str(k)):
                 yield res
     elif isinstance(obj, list):
         for i, v in enumerate(obj):
             for res in dot_notation(v, prefix+'['+str(i)+']'):
                 yield res
     else:
         yield prefix

例:

>>> list(dot_notation(x))
['a', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f']

标签:json,python,dictionary,nested-lists
来源: https://codeday.me/bug/20190718/1492650.html