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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With