我有以下json:
{"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代码:
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!\n"
data_temp = result.values()[0]
for key, value in data_temp.iteritems():
print key
print value
print "\n\n"
使用当前代码,我能够查看键" KqYN_VeXCh8CZQFRusI"," KqYPPffaTpft7B72Ow9"等等...以及这些键的值:
{"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
},
和
{"bathroom_temp": 20,
"date": "02/08/2017",
"fridge_level": 19,
"kitchen_temp": 14,
"living_temp": 20,
"power_bathroom": 0,
"power_bathroom_value": 0
},
我需要获取secondlevel键及其值。我试图为每个密钥设置一个文件(" bathroom_temp"," power_bathroom"等等...)并保存文件中这些密钥的所有相应值。
例如,文件" bathroom_temp.txt"将具有值#16; 16,20,23和#34;。
答案 0 :(得分:0)
您可以将JSON数据放在变量中:
data = {"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,
}
}
}
然后使用嵌套索引地址获取所需参数:
kitchen_temp = data["sensors"]["-KqYN_VeXCh8CZQFRusI"]["kitchen_temp"]
print(kitchen_temp)