2017-10-17 68 views
1

我必須建立一個Json數據庫(Firebase實時數據庫)的分析系統。 這裏是什麼樣子:遞歸解析多個json對象來練習計算 - Python

{ 
    "247" : { 
    "activity_duration" : 15, 
    "battery_used" : 0, 
    "date" : "2017-09-05", 
    "day" : 247, 
    "heat_waves" : 3, 
    "outside_temperature" : 16.64, 
    "shirt_temperature" : [ 24.883928571428573, 23.660714285714285 ] 
    }, 
    "262" : { 
    "activity_duration" : 240, 
    "battery_used" : 2, 
    "date" : "2017-09-20", 
    "day" : 262, 
    "heat_waves" : 5, 
    "outside_temperature" : 21.19, 
    "shirt_temperature" : [ 24.233616504854368, 22.954490291262136 ] 
    }, 
    "268" : { 
    "activity_duration" : 260, 
    "battery_used" : 5, 
    "date" : "2017-09-26", 
    "day" : 268, 
    "heat_waves" : 4, 
    "outside_temperature" : 16.07, 
    "shirt_temperature" : [ 18.68695652173913, 17.576630434782608 ] 
    } 
} 

要做到這一點,我想練習像一般的heat_waves我的JSON文件在Python計算。

的問題是,我不能沒有生在寫他們訪問節點。 data["247"]["heat_waves"]但我想是這樣data[0]["heat_waves"]。當我嘗試:

import json; 

data = [ ]; 
filename = "Database.json"; 
with open(filename,'r') as json_data: 
    data = json.load(json_data); 
    print(json.dumps(data[0]["heat_waves"], indent=4, sort_keys=True)); 

我有這樣的錯誤消息:

print(json.dumps(data[0]["heat_waves"], indent=4, sort_keys=True)); KeyError: 0

所以,我的最後一個問題是:

如何訪問這些節點沒有生寫呢?

回答

0

如果你不想通過鍵來解決元素但隨着指數那麼你可以做

>>> import json; 
>>> 
>>> data = [ ]; 
>>> filename = "Database.json"; 
>>> with open(filename,'r') as json_data: 
...  data = json.load(json_data) 
>>> data.values()[0]['heat_waves'] 
5 
>>>