Created
July 30, 2013 20:41
-
-
Save mittenchops/6116718 to your computer and use it in GitHub Desktop.
This lets you get all the keys in a weirdly nested json document. Very useful for working with mongodb. Works like variety.js but at the item-level.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def listNkeys(obj, prefix=''): | |
""" | |
This lets you list ALL the keys of large nested dictionaries a la mongodb documents. | |
from: http://stackoverflow.com/questions/17952981/return-a-list-of-all-variable-names-in-a-python-nested-dict-json-document-in-dot | |
Usage: | |
>>> x = { | |
'a': 'meow', | |
'b': { | |
'c': 'asd' | |
}, | |
'd': [ | |
{ | |
"e": "stuff", | |
"f": 1 | |
}, | |
{ | |
"e": "more stuff", | |
"f": 2 | |
} | |
], | |
'g': '' | |
} | |
>>> list(listNkeys(x)) | |
['a', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f', 'g'] | |
>>> map(partial(getByDot,x),list(listNkeys(x))) | |
['meow', 'asd', 'stuff', 1, 'more stuff', 2, ''] | |
""" | |
if isinstance(obj, dict): | |
if prefix: prefix += '.' | |
for k, v in obj.items(): | |
for res in listNkeys(v, prefix+str(k)): | |
yield res | |
elif isinstance(obj, list): | |
for i, v in enumerate(obj): | |
for res in listNkeys(v, prefix+'['+str(i)+']'): | |
yield res | |
else: | |
yield prefix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment