簡體   English   中英

從嵌套的json數據中提取和格式化值

[英]Extract and format Values from nested json data

我正在嘗試使用Python 2.7.9從下面的json數據框中提取一些數據。

我正在嘗試使用以下代碼來獲取“步驟”列表中列出的單行計數:

data2 = (json.loads(data));

for data_key,data_value in data2['data'].items():
for date_key,date_value in data_value.items():
    for steps_value in date_value:
        if 'steps' == date_key:    #looping on dictionary object
            print data_key,steps_value['count'],steps_value['event'],steps_value['custom_event']

在進一步挖掘時,我設法取得了一些進展並實現了價值觀。 我不是Python專家,所以想知道是否可以以更優雅的方式進行操作。仍然希望獲得如下輸出。

理想的輸出格式:
日期1步驟1計數1步驟2計數2
日期2步驟2計數1步驟2計數2

樣本數據框:

"frame": 
{"dates": ["2016-09-12", "2016-09-19", "2016-09-26"]}, 
"data": {
    "2016-09-12": 
        {"steps": [
            {"count": 325788, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"}, 
            {"count": 20524, "step_conv_ratio": 0.627875673029858, "goal": "Game Played", 
            "avg_time": 572, "event": "Game Played"}], 
        "analysis": {"completion": 20524, "starting_amount": 32688, "steps": 2, "worst": 1}}, 
    "2016-09-19": 
        {"steps": [
            {"count": 32186, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"}, 
            {"count": 20809, "step_conv_ratio": 0.6405528535369082, "goal": "Game Played", 
            "avg_time": 698, "event": "Game Played"}], 
        "analysis": {"completion": 20809, "starting_amount": 32486, "steps": 2, "worst": 1}}, 
    "2016-09-26": 
        {"steps": [
            {"count": 456, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"}, 
            {"count": 587, "step_conv_ratio": 0.7873688132646091, "goal": "Game Played", 
            "avg_time": 571, "event": "Game Played"}], 
        "analysis": {"completion": 12679, "starting_amount": 16103, "steps": 2, "worst": 1}}
    }} 

任何幫助/建議,將不勝感激。

謝謝

如果每個日期只有兩個步驟,則可以執行以下操作:

stuff = json.loads(data)
dates = stuff["frame"]["dates"] # list of dates as strings
for date in dates:
    steps = stuff["data"][date]["steps"] # list of dicts
    print("{0}: step 1: {1}, step 2: {2}".format(date, steps[0]["count"], steps[1]["count"]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM