使用 jquery 迭代 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8277085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:16:11  来源:igfitidea点击:

Iterate JSON object with jquery

jqueryjson

提问by el_pup_le

Why isn't the following working, inside a loop it never prints the url when myJSON is empty or not.

为什么以下不起作用,在循环中,无论 myJSON 是否为空,它都不会打印 url。

$.each($.parseJSON(myJSON), function(key,value){
    alert(value.url);
});

for this JSON structure:

对于这个 JSON 结构:

[{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]

Edit: $.each is inside a loop which has instances/iterations where myJSON is empty if that makes a difference.

编辑: $.each 位于一个循环内,该循环具有实例/迭代,其中 myJSON 为空,如果这有所不同。

回答by Dogbert

This works for me.

这对我有用。

var myJSON = '[{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]';

$.each($.parseJSON(myJSON), function(key,value){
    alert(value.url);
});

回答by JN_newbie

var data = [{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]

$.each(data, function(i, item) {
    alert(data[i].host);
});?

same as with the url.

与网址相同。