我有一个相当大的JSON对象,看起来像这样:
[
{
"FoodNumber":"95809548",
"FoodIdentification":"Food Name",
"StockCode":"710",
"Description":
[
"Blah blah blah",
"More blah blah blah"
]
},
{
"FoodNumber":"95892541",
"FoodIdentification":"Another food name",
"StockCode":"710",
"Description":
[
"Food description here",
"Additional description here"
]
},
{
"FoodNumber":"97179370",
"FoodIdentification":"Yet another food name",
"StockCode":"602",
"Description":[]
},
{
"FoodNumber":"97270901",
"FoodIdentification":"HEY",
"StockCode":"602",
"Description":[]
}
]
如您所见,有时描述是空的,有时它有多个项目。我目前的jQuery代码如下:
$("#SearchQueryButton").click(function () {
$.ajax({
url: "TestMe.aspx/PopulateMainTable",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
min: 1,
max: 25,
searchQuery: $("#SearchQueryTextbox").val()
}),
dataType: "json",
beforeSend: function (html) {
$('#initial_results').html('');
},
success: function (html) {
//console.log(html);
$.each(html.d, function (i, obj) {
console.log(obj);
});
//$('#initial_results').append(html);
}
});
});
});
如果我用以下任何一行替换“ console.log(obj); ”:
1) console.log(html[i].FoodNumber);
2) console.log(obj.FoodNumber);
我得到了与使用 console.log(obj); :
相同的确切错误Uncaught TypeError: Cannot use 'in' operator to search for '4579' in <insert giant blob of json here>
我已经尝试过一个JSON验证器来确定它是否是一个有效的blob,它确实是。我正在使用与上面列出的完全相同的JSON blob,但删除了描述文本。我该如何正确解析这个?它是一个相当大的JSON字符串,大小约为4.52 KB,我在解析它时遇到问题,因此我可以将其显示给用户。
谢谢!
答案 0 :(得分:1)
最后,经过一段时间的调试后,我找到了解决我遇到的每个问题的方法:
1)需要使用 $。parseJSON(z.d);
将字符串转换为jsonvar json = $.parseJSON(z.d);
2)我需要&#34; 返回false; &#34;在函数结束之前,它不会刷新并丢失所有内容(请注意,initial_results不再是id,而是一个类)。
现在我拥有了我需要的一切。完整代码如下:
$("#SearchQueryButton").click(function () {
$.ajax({
url: "TestMe.aspx/PopulateMainTable",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
min: 1,
max: 25,
searchQuery: $("#SearchQueryTextbox").val()
}),
dataType: "json",
beforeSend: function (html) {
$('.initial_results').html('');
},
success: function (z) {
var json = $.parseJSON(z.d);
$.each(json, function (i, obj) {
console.log(obj);
});
},
error: function(e)
{
$('.initial_results').html("Error:" + e.toString());
}
});
return false;
});
});
答案 1 :(得分:0)
在json中你可以简单地使用它来访问属性,如下所示:
$.each(html.d, function () {
console.log(this.FoodNumber);
});
你确定数组是在html.d中吗?我们这里没有服务器端代码。