给定未知长度的路径( foos )和相关值( bars ):
foo1 = '/path/key1'
foo2 = '/path/node1/key2'
bar1 = 'value1'
bar2 = 'value2'
如何递归地将这些映射到json结构,例如使用python的json模块?以上将成为:
{ 'path':
{ 'key1': 'value1',
'node1': { 'key2': 'value2' }
}
}
前面提到的json模块支持:
json_data['path']['key1'] = bar1
json_data['path']['node1']['key2'] = bar2
但我不知道所提供的每条路径的深度......?!
答案 0 :(得分:2)
要获取递归字典,可以使用此帮助程序类
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)
def __getitem__(self, item):
if isinstance(item, (tuple, list)):
cur = self[item[0]]
for i in item[1:]:
cur = cur[i]
return cur
else:
return super(RecursiveDict, self).__getitem__(item)
def __delitem__(self, item):
if isinstance(item, (tuple, list)):
cur = self[item[0]]
for i in item[1:-1]:
cur = cur[i]
del cur[item[-1]]
else:
return super(RecursiveDict, self).__delitem__(item)
使用类似:
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}