I have an AJAX call, which calls a controller. This controller returns the following JSON:
{"officeProducts":"[{\"Id\":96,\"MyProperty\":null,\"Enabled\":true,\"Envelope\":{\"Id\":1,\"Quality\":\"God\",\"PaperSize\":\"A4\",\"Type\":\"Window\"}},{\"Id\":169,\"MyProperty\":null,\"Enabled\":true,\"Envelope\":{\"Id\":1,\"Quality\":\"God\",\"PaperSize\":\"A4\",\"Type\":\"Window\"}},{\"Id\":174,\"MyProperty\":null,\"Enabled\":true,\"Envelope\":{\"Id\":1,\"Quality\":\"God\",\"PaperSize\":\"A4\",\"Type\":\"Window\"}},{\"Id\":175,\"MyProperty\":null,\"Enabled\":true,\"Envelope\":{\"Id\":1,\"Quality\":\"God\",\"PaperSize\":\"A4\",\"Type\":\"Window\"}}]"}
And now I want to iterate the list. So I basically want to iterate the officeProducts.
I have the following code, where I obviously do something wrong, as I get a:
Error:
Error: Syntax error, unrecognized expression: [{"Id":96,"MyProperty":null,"Enabled":true,"Envelope":{"Id":1,"Quality":"God","PaperSize":"A4","Type":"Window"}},{"Id":169,"MyProperty":null,"Enabled":true,"Envelope":{"Id":1,"Quality":"God","PaperSize":"A4","Type":"Window"}},{"Id":174,"MyProperty":null,"Enabled":true,"Envelope":{"Id":1,"Quality":"God","PaperSize":"A4","Type":"Window"}},{"Id":175,"MyProperty":null,"Enabled":true,"Envelope":{"Id":1,"Quality":"God","PaperSize":"A4","Type":"Window"}}]
My AJAX call:
self.updateOfficeProducts = function() {
$.ajax({
url: '/SingleLetter/GetOfficeProducts',
type: 'POST',
data: {
'country': self.countryId
},
dataType: 'json',
success: function (data) {
console.log(data.officeProducts);
$(data.officeProducts).each(function (index, ele) {
alert(ele.Id);
});
}
});
};
So I would expect to iterate 4 different objects, where I can say things like ele.Id or ele.Enabled. Instead I get my syntax error.
What am I doing wrong? :-) Obviously some syntax thing.
Use JSON.parse-
success: function (data) {
data = JSON.parse(data);
$(data.officeProducts).each(function (index, ele) {
alert(ele.Id);
});
...
Edit
Another thing — I'm not sure of .NET, but the response you're getting back is not of the form expected by ajax. The string is not properly json-encoded.
You have to remove " before and after the [ and ], so the string would be-
var a = '{"officeProducts": [{\"Id\":96,\"MyProperty\":null,\"Enabled\":true,\"Envelope\":{\"Id\":1,\"Quality\":\"God\",\"PaperSize\":\"A4\",\"Type\":\"Window\"}}] }';
// ^here and here^
JSFiddle
Hope that helps.
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