I'm currently working on parsing JSON data with JavaScript, but I've hit a roadblock when trying to access the value that is part of the first PWER object (the value changes and I simply want to display it on the webpage). Additionally, the '1452520496000' portion also changes based on time. As someone new to JavaScript and JSON, I find the examples I have come across during my research to be relatively straightforward compared to this particular case where I need to access the PWER in "cid": "PWER".
Below is an excerpt of the JSON output received from the API:
[
{"cid":"PWER",
"data":[{"1452520496000":568}],
"sid":"144",
"units":"kWm",
"age":5
},
{"cid":"MOTN",
"data":[{"1452520489000":0}],
"sid":"910",
"units":"S",
"age":12
},
{"cid":"LGHT",
"data":[{"1452520489000":19.09}],
"sid":"910",
"units":"L",
"age":12}
]
In order to tackle this challenge, I have adopted code snippets from the example provided here as a foundation for the HTTP GET request while I figure out how to parse the JSON data efficiently. Here's what I have managed to put together so far:
<div id="main"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "URLGoesHere";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var out = arr[0].data[0];
document.getElementById("main").innerHTML = out;
}
</script>
The problem I am facing is that instead of displaying the desired result, my page shows [object Object].
To troubleshoot, I've been using the console:
console.log(arr[0]);
Object {cid: "PWER", data: Array1, sid: "144", units: "kWm", age: 5}
This confirms that the API token is successfully accessed and data is being retrieved.
In order to dig deeper into the retrieved data, I check the contents of 'Array1' within 'data':
console.log(arr[0].data);
[Object]
0: Object
length: 1
__ proto __: Array[0]
My next step involves trying to access the object at index 0:
console.log(arr[0].data[0]);
Object {1452520496000: 568}
The desired value of 568 is present, however, I am unable to access it due to the ever-changing nature of the '1452520496000' parameter. What would be the most effective approach to accessing this value?