1

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.

Parse JSON in 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.

1
  • You can use this to help you visualize your JSON: json.parser.online.fr Commented Aug 15, 2011 at 19:13

2 Answers 2

3

The JSON data (which is an object) only contains one element: mainunit.

You don't need the $.each. Just do:

data.mainunit.sensors[0].tc; // 71.3

Your $.each will loop just once, and in that loop learning will be data.mainunit.

$.each(data, function(i, learning) {
    alert(i); // 'mainunit'
    alert(data.sensors[0].tc); // 71.3
});

EDIT: To loop through each sensor:

$.each(data.mainunit.sensors, function(i, sensor) {
    alert(sensor.tc);
});
Sign up to request clarification or add additional context in comments.

1 Comment

I would use $.each to loop through each of the sensors right?
0

JSON objects need starting and ending brackets, and what you have in your file is a JSON object (a key/pair value).

6 Comments

I thought his question was "but if I remove the beginning and ending square brackets it won't parse. Can someone clarify why."
Ah, I just noticed that he was accessing the object incorrectly, I didn't see that part. BTW: JSON needs opening/closing brackets.
I beg to differ. JSON.stringify([1, 2, 3]);
JSON.stringify([1, 2, 3]) = '[1,2,3]'. As you can see it has [ and ] around it. Those are opening/closing brackets.
Right. We have a different word for them in french, got me confused. You're right.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.