我想通过循环访问json中存在的alias
和dims
的内部元素metrics
值,并附加在单独的dimsList
和metricsList
python中列表。
json_obj =
{
"dataset":"246",
"dims":{
"Location":{
"alias":"Location",
"format":""
}
},
"metrics":{
"ToTal_Dwell":[
{
"agg":"sum",
"format":"",
"alias":"ToTal_Dwell"
}
]
},
"filters":"",
"limit":"10"
}
预期结果类似于dimsList = ['Location']
和metricsList = ['ToTal_Dwell']
答案 0 :(得分:1)
您可以使用.items()
进行递归迭代。每次看到内部字典时,您都会进行递归调用,并且内部列表会导致列表中每个内部字典都发生调用。
尝试一下:
json_obj = {
"dataset": "246",
"dims": {
"Location": {
"alias": "Location",
"format": ""
}
},
"metrics": {
"ToTal_Dwell": [
{
"agg": "sum",
"format": "",
"alias": "ToTal_Dwell"
}
]
},
"filters": "",
"limit": "10"
}
def extract_inner_values(d, key):
results = []
for k, v in d.items():
if k == key:
results.append(v)
if isinstance(v, dict):
results.extend(extract_inner_values(v, key))
if isinstance(v, list):
for inner_d in v:
results.extend(extract_inner_values(inner_d, key))
return results
dimsList = extract_inner_values(json_obj["dims"], "alias")
metricsList = extract_inner_values(json_obj["metrics"], "alias")
print(dimsList)
print(metricsList)
输出:
['Location']
['ToTal_Dwell']