GMeister GMeister - 3 months ago 7
Python Question

In python, apply path (URL) of unknown length to a JSON object

Given paths (foos) of unknown length, and associated values (bars):

foo1 = '/path/key1'
foo2 = '/path/node1/key2'
bar1 = 'value1'
bar2 = 'value2'


How can I recursively map these to a json structure, for example using python's json module? The above would become:

{ 'path':
{ 'key1': 'value1',
'node1': { 'key2': 'value2' }
}
}


The aforementioned json module supports:

json_data['path']['key1'] = bar1
json_data['path']['node1']['key2'] = bar2


But I don't know the depth of each path provided...?!

Answer

To get a recursive dictionary, you can use this helper class

class RecursiveDict(dict):
    def __missing__(self, attr):
        db = RecursiveDict()
        super(RecursiveDict, self).__setitem__(attr, db)
        return db

    def __setitem__(self, attr, value):
        if isinstance(attr, (tuple,list)):
            cur = self[attr[0]]
            for i in attr[1:-1]:
                cur = cur[i]
            cur[attr[-1]] = value
        else:
            super(RecursiveDict, self).__setitem__(attr, value)

Use like:

a=RecursiveDict()

path="/a/a/a"
path = path.strip("/").split("/")

a[path]="value"
a["a","b","c"]=1
a["b"]=2
print a

--> {'a': {'a': {'a': 'value'}, 'b': {'c': 1}}, 'b': 2}