I am trying to parse this test.json (It does validates, so that doesn’t appear to be an issue, it’s in the same folder as the file containing the javascript below)
{
"mainunit": {
"sensors": [
{
"id": "C9",
"name": "Sensor 2",
"tc": 71.3,
"pair": null
},
{
"id": "4A",
"name": "Sensor 1",
"tc": 106.7,
"pair": null
}
],
"fans": null
}}
I’m trying to use this . . .
$.getJSON('test.json',function(data) {
$.each(data, function(i, learning) {
alert(learning.mainunit.sensors[0].tc);
});});
This code is from a previous SO question, see link below.
I also have a general questions about this previous question regarding parsing json with jQuery.
I can get this example to parse, but if I remove the beginning and ending square brackets it won’t parse. Can someone clarify why. It appears that json doesn’t need beginning and ending square brackets.
Thanks in advance.
The JSON data (which is an object) only contains one element:
mainunit.You don’t need the
$.each. Just do:Your
$.eachwill loop just once, and in that looplearningwill bedata.mainunit.EDIT: To loop through each sensor: