Javascript通过索引迭代json

时间:2013-09-11 19:33:56

标签: javascript json

我正在尝试编写一个循环来直接访问这个json数组的元素,我已经在这里和其他地方找到了一些示例,它们显示了json数据的迭代,但我没有任何工作,也使用索引。

http://jsfiddle.net/rfVGW/

我一直在寻找在循环中执行以下操作,我实际上json是在单行上(请参阅jsfiddle):

alert(jsonData.data[0].serviceType);

可读的json字符串

{
"data": [{
    "id": "1",
    "serviceType": "test",
    "firstName": "",
    "lastName": "",
    "address1": "",
    "address2": "",
    "address3": "",
    "city": "",
    "county": "",
    "postCode": "",
    "website": "",
    "latitude": "",
    "longitude": "",
    "phoneArr": ["00001", "000002"]
}, {
    "id": "1",
    "serviceType": "",
    "firstName": "",
    "lastName": "",
    "address1": "",
    "address2": "",
    "address3": "",
    "city": "",
    "county": "",
    "postCode": "",
    "website": "",
    "latitude": "",
    "longitude": "",
    "phoneArr": ["00001", "000002"]
}]
}

1 个答案:

答案 0 :(得分:1)

以下是更新后的fiddle

您没有将变量解析为JSON。

所以请使用 JSON.parse();

来完成
var par = JSON.parse(jsonData);
alert(par.data[0].serviceType);