I am building an air app that needs to access data from Firebase Database using the REST API. I am able to get the data but I do not know how to get the information I need from that data.
Basically, I have an Android app and a Desktop app. The android app uploads/Modifies data and the Desktop app needs to access that data and send signals to the ESP8266 via a socket connection. I have a list of 'Lights' each light as a 'lightname', 'status' and 'pin'. I want to be able to loop through all the 'pin's.
When I try to get the data , I get this JSON:
{"-LAb_YKS9l7qQno25AY5":{"lightname":"light1","pin":"14","status":"on","timestamp":1524303808146},"-LAb_cRpsGpQfr7JbCfI":{"lightname":"light2","pin":"15","status":"on","timestamp":1524303830159},"-LAb_zbf2sYuyTtW_uEr":{"lightname":"blah","pin":"9","status":"on","timestamp":1524303921921},"-LAba68lzyG15n6anuSF":{"lightname":"dishl","pin":"7","status":"on","timestamp":1524303955946},"-LAdZW2JjQVGfLMc_sb4":{"lightname":"cxcxc","pin":"14","status":"on","timestamp":1524337092712}}
I want to loop through all the lights and access their 'pin' values. Here is what i've tried:
for (var i:int = 0; i < e.target.data.length; i++)
{
trace(e.target.data[i]["status"]);
}
I get this error:
Property 0 not found on String and there is no default value.
Any help is greatly appreciated.
Because the e.target.data answer you get from Firebase is a String and first you need to JSON.parse(...) it to transform it into data. Then your data is not an Array, it is an Object. You loop through it as following:
// Parse the incoming data.
var aData:Object = JSON.parse(e.target.data);
// Loop through string keys of the data object.
for (var aKey:String in aData)
{
trace("");
trace(aKey);
// Assign entry reference to another local variable. This is not
// mandatory, but the following code is shorter and thus more readable.
var anEntry:Object = aData[aKey];
trace(anEntry['pin']);
trace(anEntry['status']);
trace(anEntry['lightname']);
}
If you have no use of key values, you might do it in a slightly different way:
// Parse the incoming data.
var aData:Object = JSON.parse(e.target.data);
// Loop through values of the data object while ignoring the keys.
for each (var anEntry:Object in aData)
{
trace("");
trace(anEntry['pin']);
trace(anEntry['status']);
trace(anEntry['lightname']);
}