使用嵌入式数组迭代JSON

Iterating JSON with embedded array

本文关键字:迭代 JSON 数组 嵌入式      更新时间:2023-09-26

我有以下JSON:

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

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

要将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]
    }
}

我特别喜欢这里和这里描述的$.parseJSON