Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery JSON parse returns undefined

Tags:

json

jquery

I'm trying to parse a JSON string but when I do I get undefined.

var codes = jQuery.parseJSON(response);

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

Here is the contents of codes variable above:

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

alert returns value.Display as undefined. I expected "String1". What am I doing wrong?

like image 574
Eren Avatar asked Dec 03 '25 17:12

Eren


2 Answers

That's not a valid JSON string.
A correct string would look like this:

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

You can't. There is no Display property in the array, it's an array containing two strings.

The strings are similar to JSON, but not enough to be parsed.

If you make the strings follow the JSON standard, you can parse each item in the array into an object, then you can access the Display property:

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);
});

Demo: http://jsfiddle.net/Guffa/wHjWf/

Alternatively, you can make the entire input follow the JSON standard, so that you can parse it into an array of objects:

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);
});

Demo: http://jsfiddle.net/Guffa/wHjWf/1/

like image 28
Guffa Avatar answered Dec 06 '25 08:12

Guffa