想要使用循环获取json的内部元素

时间:2019-07-16 11:25:54

标签: python json

我想通过循环访问json中存在的aliasdims的内部元素metrics值,并附加在单独的dimsListmetricsList 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']

1 个答案:

答案 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']