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

Mit*_*ops 3 python json dictionary nested-lists

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

x = {
    'a': 'meow',
    'b': {
        'c': 'asd'
    },
    'd': [
        {
            "e": "stuff",
            "f": 1
        },
        {
            "e": "more stuff",
            "f": 2
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

mylist = f(x) 会回来......

>>> mylist
['a', 'b', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f']
Run Code Online (Sandbox Code Playgroud)

And*_*ark 5

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
Run Code Online (Sandbox Code Playgroud)

例:

>>> list(dot_notation(x))
['a', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f']
Run Code Online (Sandbox Code Playgroud)