Smoothing a list of dicts of lists of dicts (etc.) of unknown depth in Python (a nightmarish JSON structure)

I am dealing with a JSON structure, which is displayed to me in such structures:

[{u'item': u'something',
  u'data': {
            u'other': u'',
            u'else':
               [
                  {
                    u'more': u'even more',
                    u'argh':
                         {
                            ...etc..etc

As you can see, these are nested dicts and lists. There are many discussions about smoothing these out recursively, but I have not yet found one that can deal with a list of dictionaries, which, in turn, can contain either list dictionaries, list lists, dictionary dictionaries, etc .; which have an unknown depth! In some cases, the depth can be up to 100 or so. I have tried this so far without much luck (python 2.7.2):

def flatten(structure):
    out = []
    for item in structure:
        if isinstance(item, (list, tuple)):
            out.extend(flatten(item))
        if isinstance(item, (dict)):
            for dictkey in item.keys():
                out.extend(flatten(item[dictkey]))
        else:
            out.append(item)
    return out

Any ideas?

UPDATE This pretty much works:

def flatten(l):
    out = []
    if isinstance(l, (list, tuple)):
        for item in l:
            out.extend(flatten(item))
    elif isinstance(l, (dict)):
        for dictkey in l.keys():
            out.extend(flatten(l[dictkey]))
    elif isinstance(l, (str, int, unicode)):
        out.append(l)
    return out
+5
source share
1 answer

, , . , , .

for key in sorted(dic_.keys()), .

, "" .

def flatten(structure, key="", path="", flattened=None):
    if flattened is None:
        flattened = {}
    if type(structure) not in(dict, list):
        flattened[((path + "_") if path else "") + key] = structure
    elif isinstance(structure, list):
        for i, item in enumerate(structure):
            flatten(item, "%d" % i, path + "_" + key, flattened)
    else:
        for new_key, value in structure.items():
            flatten(value, new_key, path + "_" + key, flattened)
    return flattened
+9

All Articles