0
我有以下的JSON:如何獲得使用javascript從多層次的JSON值,而無需知道鍵
from flask import Flask, render_template, json, url_for
from firebase import firebase
import os
firebase = firebase.FirebaseApplication('https://my-firebase-db-958b1.firebaseio.com/', None)
result = firebase.get('/Dublin-Ireland', None)
print "\n Json file created!"
with open ('data.txt', 'w') as outfile:
json.dump(result, outfile)
app = Flask(__name__)
@app.route('/')
def homepage():
with open('data.txt') as f:
s = f.read()
return render_template("homepage.html" , nameTxt = s)
if __name__ == "__main__":
app.run()
:
{"sensors":
{"-KqYN_VeXCh8CZQFRusI":
{"bathroom_temp": 16,
"date": "02/08/2017",
"fridge_level": 8,
"kitchen_temp": 18,
"living_temp": 17,
"power_bathroom": 0,
"power_bathroom_value": 0,
"power_kit_0": 0
},
"-KqYPPffaTpft7B72Ow9":
{"bathroom_temp": 20,
"date": "02/08/2017",
"fridge_level": 19,
"kitchen_temp": 14,
"living_temp": 20,
"power_bathroom": 0,
"power_bathroom_value": 0
},
"-KqYPUld3AOve8hnpnOy":
{"bathroom_temp": 23,
"date": "02/08/2017",
"fridge_level": 40,
"kitchen_temp": 11,
"living_temp": 10,
"power_bathroom": 1,
"power_bathroom_value": 81,
}
}
}
我從一個文件中使用以下Python文件讀取它
我可以將json數據從python文件傳遞給javascript。解析後,我可以使用JSON.Stringify查看所有值。但是,我一次無法獲得一個價值。我試圖做的是將每個密鑰保存在自己的文件中(例如,bathroom_temp,date,fridge_level等),並在json以週期性方式更新時追加值。因此,稍後我可以獲取我需要的任何關鍵數據並使用數據繪製折線圖。例如,bathroom_temp文件應該包含「16,20,23」,並且這可以用於繪製圖形。
以下是我的javascript代碼:
<script>
var test = JSON.parse({{ nameTxt|tojson }});
for(key in test)
{
if(test.hasOwnProperty(key))
{
var value = test[key];
alert(JSON.stringify(value, null, 4));
}
}
</script>