如何像对象一样操纵Json响应?

我的jQuery.ajax返回JSon对象。 我首先阅读其他文章。 但他们的回应文字并不喜欢我的。 我的回复内容 :来自firebug的回应

{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"} 

现在我试图提醒countryName:

 $('#loadData').click(function() { $.ajax({ type: "POST", url: "WS/myWS.asmx/getDaa", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { $("#jsonResponse").html(msg); $.each(msg.item, function(i, d) { alert(this.country); debugger; }); }, }); }); 

但它警告“未定义”

item的值是一个字符串。 因此,您首先需要将其解析为json。 试试这个。

 $("#jsonResponse").html(msg); var item = jQuery.parseJSON(msg.item) $.each(item, function(i, d) { alert(this.country); debugger; }); }, 
 {"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"} ^ | +---- It's a string, not an array ! 

你的JSON应该是这样的

 {"item":[ {"country":"USA","lan":"EN"},{"country":"Turkiye","lan":"TR"}]} 

然后你可以像访问它一样

 country = msg.item[0]; lang = country.lan; for (i=0; i< item.length; i++) { alert ( item[i].country); } 

等等...

原因是msg.item是一个字符串。

它是一个字符串的原因是你在item:之后的初始双引号item: 。 这也解释了为什么你的双引号被转义。 你有:

 {"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"} 

当你应该:

 {"item":[{"country":"USA","lan":"EN"},{"country":"Turkiye","lan":"TR"}]"}