在 JavaScript 中的 JSON 中迭代

Iterating in a JSON in javascript

本文关键字:迭代 JSON 中的 JavaScript      更新时间:2023-09-26

我有一个看起来像下面的JSON。

[
{"Device":"Device1","Links"["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"}
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
]

我想遍历它,并在循环中提醒链接字段的值。

我怎样才能做到这一点。

如果你有一个 json 作为字符串,你可以使用

var json = JSON.parse(jsonString); 

这将返回一个可以迭代的对象数组。

在此处查看更多内容

var arr = [
   {"Device":"Device1","Links" ["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
   {"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"}
   {"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
];
    for(var i=0;i<arr.length;i++){
        var obj = arr[i];
        for(var key in obj){
            var attrName = key;
            var attrValue = obj[key];
        }
    }

假设你有你的字符串json

var data = JSON.parse(json);
for(var i=0; i<data.length; i++) {
    var links = data[i]['Links'];
    for(var j=0; j<links.length; j++) {
        //append this wherever
        document.write(links[j]);
        //if you're using jQuery, $('body').append(links[j]);
    }
}
[
{"Device":"Device1","Links":["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"},
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
]
var json = JSON.parse(jsonString); 

现在它将工作

您在 JSON 字符串中遗漏了 ":"和 " , "

在第一个"链接":和 } 附近添加此内容

var json = [
    {
        "Device": "Device1",
        "Links": [
            "NewLink",
            "NewLink2",
            "NewLink3"
        ],
        "GeographicLocation": "NewLocation"
    },
    {
        "Device": "Device2",
        "Links": [
            "NewLink"
        ],
        "GeographicLocation": "NewLocation"
    },
    {
        "Device": "Device3",
        "Links": [
            "NewLink",
            "NewLink2"
        ],
        "GeographicLocation": "NewLocation"
    }
];
for(var i=0; i<json.length ; i++)
{
    console.log(json[i].Device);
    console.log(json[i].Links);
    // for links use another loop
    for(var j=0; j<json[i].Links.length ; j++)
    {
        console.log(json[i].Links[j]);
    }
    console.log(json[i].GeographicLocation);
}