GMeister GMeister - 1 year ago 83
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 Source

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
            super(RecursiveDict, self).__setitem__(attr, value)

Use like:


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

print a

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download