-1

I have the following JSON:

[
    {
        "id": "1",
        "selected": true,
        "question": "Which of the following does <b><i>not</i></b> describe Washington’s location?",
        "answers": {
            "A": {
                "selector": "A",
                "answerText": "It is in the northwest corner of the United States.",
                "correct": "N"
            },
            "B": {
                "selector": "B",
                "answerText": "The Pacific Ocean provides the western border.",
                "correct": "N"
            },
            "C": {
                "selector": "C",
                "answerText": "It is north of Oregon and west of Idaho.</span>",
                "correct": "N"
            },
            "D": {
                "selector": "D",
                "answerText": "A natural boundary can be created by a river.",
                "correct": "Y"
            }
        }
    },
    {
        "id": "2",
        "selected": true,
        "question": "Which of the following best describes a spatial pattern in Washington?",
        "answers": {
            "A": {
                "selector": "A",
                "answerText": "Most people settled along rivers and water in the fertile valleys.",
                "correct": "Y"
            },
            "B": {
                "selector": "B",
                "answerText": "Most people settled high in the mountains to protect themselves from their enemies.",
                "correct": "N"
            },
            "C": {
                "selector": "C",
                "answerText": "Most people settled at the base of the Rocky Mountains. They couldn’t travel any further.",
                "correct": "N"
            },
            "D": {
                "selector": "D",
                "answerText": "Most people settled along the Pacific Rim because it was a good place to trade.",
                "correct": "N"
            }
        }
    }
]

What is the best way to iterate through the object? Should I use jquery or straight javascript? Any example would be great...

Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
lascoff
  • 1,321
  • 4
  • 17
  • 35

2 Answers2

2

To parse a JSON string to an object use

JSON.parse(str);

To iterate through an array, use

for(var i=0, l=arr.length; i<l; ++i) {
    // Here use arr[i]
}

To iterate through an object, use

for(var i in obj) {
    if(obj.hasOwnProperty(i)) {
        // Here use obj[i]
    }
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

I am particular to $.parseJSON as described here and here.

Vidya
  • 29,932
  • 7
  • 42
  • 70