使用嵌入式数组迭代JSON

时间:2013-11-19 01:09:43

标签: javascript jquery json

我有以下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"
            }
        }
    }
]

迭代对象的最佳方法是什么?我应该使用jquery还是直接javascript?任何一个例子都会很棒......

2 个答案:

答案 0 :(得分:2)

要将JSON字符串解析为对象,请使用

JSON.parse(str);

要遍历数组,请使用

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

要遍历对象,请使用

for(var i in obj) {
    if(obj.hasOwnProperty(i)) {
        // Here use obj[i]
    }
}

答案 1 :(得分:1)

herehere所述,我特别关注$.parseJSON