我有一个从REST服务返回的JSON,我希望通过组合父键为每个值生成一个唯一的名称。例如。 name+phone+address+city+name
,name+phone+address+city+population+skilled+male
等等。
{
"name": "name",
"phone": "343444444",
"address": {
"lat": 23.444,
"lng": 34.3322,
"city":{
"name": "city name",
"population": {
"skilled": {
"male": 2,
"female": 4
},
"uneducated": {
"male": 20,
"femail": 4
}
}
}
},
"email": "email",
"education": "phd"
}
我想组合从JSON树的父级开始的所有键名。
这就是我正在做的事情
class TestJson
def walk_through(self, json_object):
for k, v in json_object.items():
self.x_path = self.x_path + k
if type(v) is dict:
self.walk_through(v)
else:
print(self.x_path)
self.x_path = ""
此代码是打印密钥,但仅从当前父节点开始。我想将所有密钥组合到json的根目录。
答案 0 :(得分:1)
如果忽略name
和phone
键,因为它们不是city name
或skilled male
的祖先,并且无法保证键的顺序,您可以递归构建扁平的字典。
def walk_through(json_object):
d = {}
for k, v in json_object.items():
if isinstance(v, dict):
v = walk_through(v)
for vk, vv in v.items():
d["%s+%s" % (k, vk)] = vv
else:
d[k] = v
return d
print(json.dumps(walk_through(json_object), indent=2))
打印:
{
"address+city+population+skilled+male": 2,
"name": "name",
"address+lng": 34.3322,
"address+city+name": "city name",
"address+lat": 23.444,
"address+city+population+uneducated+male": 20,
"phone": "343444444",
"address+city+population+uneducated+femail": 4,
"education": "phd",
"email": "email",
"address+city+population+skilled+female": 4
}
注意:这会忽略列表,但不会在其中找到dicts。
答案 1 :(得分:0)
如果要打印python dict的所有键,可以执行以下操作:
def print_keys(d):
for key, value in d.iteritems():
print key,
if isinstance(value, dict):
print_keys(value)