我有几个json,我需要找到每个关键的连续父母。下面是一个json示例
{
"status": 0,
"body": {
"activities": [
{
"date": "2018-12-12",
"data": [
{
"cid": 1,
"steps": 313
},
{
"cid": 2,
"steps": 345
},
{
"cid": 3,
"steps": 577
}
]
},
{
"date": "2018-12-14",
"data": [
{
"cid": 1,
"steps": 313
},
{
"cid": 2,
"steps": 345
},
{
"cid": 3,
"steps": 577
}
]
}
],
"more": false,
"offset": 200
}
}
使用
keys_list = get_all_keys(my_json)
keys_list = list(dict.fromkeys(keys_list))
我可以获取json中的所有键,例如['status'、'body'、'activities'、'date'、'data'、'cid'、'steps'、'more'、'offset'] 但我也希望得到每个键的连续父母和类型如下
For activities key: {{body.activities[]}}
For data key: {{body.activities[].date}}
For cid key: {{body.activities[].data[].cid}}
For steps key: {{body.activities[].data[].steps}}
[]符号表示其字典类型键
我使用一个函数
def find_path(dict_obj,key,i=None):
for k,v in dict_obj.items():
# add key to path
path.append(k)
if isinstance(v,dict):
# continue searching
find_path(v, key,i)
if isinstance(v,list):
# search through list of dictionaries
for i,item in enumerate(v):
# add the index of list that item dict is part of, to path
path.append(i)
if isinstance(item,dict):
# continue searching in item dict
find_path(item, key,i)
# if reached here, the last added index was incorrect, so removed
path.pop()
if k == key:
# add path to our result
result.append(copy(path))
# remove the key added in the first line
if path != []:
path.pop()
find_path(example2,"activities") #['body', 'activities']
find_path(example2,"cid") #['body', 'activities', 0, 'data', 0, 'cid']
寻找连续的父母。但我也需要钥匙的类型,例如
For cid key: {{body.activities[].data[].cid}}
或
['body', 'activities[]', 'data[]', 'cid']
目前没有回答
相关问题 更多 >
编程相关推荐