Jquery JSON解析返回undefined

时间:2013-01-06 15:38:34

标签: jquery json

我正在尝试解析JSON字符串,但是当我这样做时,我得到了未定义。

var codes = jQuery.parseJSON(response);

$.each(codes, function (key, value) {
  alert(value.Display);
});

以上是codes变量的内容:

["{ Display = string1, Sell = string2 }", 
 "{ Display = string1, Sell = string2 }"]

警告返回值。显示为undefined。我期待“String1”。我做错了什么?

4 个答案:

答案 0 :(得分:6)

这不是有效的JSON字符串 正确的字符串看起来像这样:

'{ "Display": "string1", "Sell": "string2" }'

答案 1 :(得分:3)

你做不到。数组中没有Display属性,它是一个包含两个字符串的数组。

字符串类似于JSON,但不足以进行解析。

如果使字符串遵循JSON标准,则可以将数组中的每个项解析为对象,然后可以访问Display属性:

var response = '["{ \\"Display\\": \\"string1\\", \\"Sell\\": \\"string2\\" }", "{ \\"Display\\": \\"string1\\", \\"Sell\\": \\"string2\\" }"]';

var codes = jQuery.parseJSON(response);

$.each(codes, function (key, value) {
  var obj = jQuery.parseJSON(value);
  alert(obj.Display);
});

演示:http://jsfiddle.net/Guffa/wHjWf/

或者,您可以使整个输入遵循JSON标准,以便您可以将其解析为对象数组:

var response = '[{ "Display": "string1", "Sell": "string2" }, { "Display": "string1", "Sell": "string2" }]';

var codes = jQuery.parseJSON(response);
console.log(codes);
$.each(codes, function (key, value) {
  alert(value.Display);
});

演示:http://jsfiddle.net/Guffa/wHjWf/1/

答案 2 :(得分:1)

我偶然通过json编码我的数组数据两次得到此错误。

像这样:

$twicefail = '{"penguins" : "flipper"}';
return json_encode( $twicefail );

然后在我看来,我这样选择了它:

var json_data = jQuery.parseJSON(my_json_response);

alert(json_data.penguins);      //Here json_data.penguins is undefined because I
                                //json_encoded stuff that was already json. 

更正后的代码如下:

$twicefail = '{"penguins" : "flipper"}';
return $twicefail;

然后在我看来,像这样捡起来:

var json_data = jQuery.parseJSON(my_json_response);

alert(json_data.penguins);     //json_data.penguins has value 'flipper'.

答案 3 :(得分:0)

您可以轻松尝试:

var json = jQuery.parseJSON(response);
//get value from response of json
var Display = json[0].Display;

您所需要的只是用于指定数据的[0],因为这是默认参数(未设置)。
它对我有用!

相关问题