Reputation: 12142
My browser (chrome) tells me this is what is being returned from the server which I have verified as being valid via JsonLint:
[{"Id":"bdd937ef-c0d4-4191-805f-316288144060","Name":"Accessories and Auto Parts, Moto ","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]},{"Id":"b01bde48-6f1d-4168-aee4-a7e62eef7bd0","Name":"Car Rental","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]},{"Id":"c039a467-1709-433f-a316-008f6ae301fb","Name":"Car Sales ","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]}]
If I just copy this content into a script var it will also parse correctly.
However if i try and parse this content, as returned from the server, into an object I get an Uncaught Syntax error:
$.ajax({
type: "POST",
url: "/Browse/SubCategoryLister/",
data: { rfqID: parentRfqId },
dataType: "json"
})
.done(function (data) {
rp.hide();
sc.show();
console.log(data);
var status = JSON.parse(data);
console.log(status);
});
On the line
var status = JSON.parse(data);
However
console.log(data);
seems to produce a valid object that I can interrogate via developer tools:
So it seems like the data is already a json object? So Im not quite sure what is going on here. I thought it might have something to do with response headers but this payload is being sent down with an:
Content-Type:application/json; charset=utf-8
header just like in other pages in the application where i use JSON.parse(data); to create a JSON object from server returned data. So what is the difference here and why cant I parse it? If it's already a JSON object then how an where was it created?
Upvotes: 1
Views: 96
Reputation: 28723
You parse json twice. Data parameters function (data)
is already javascript object, because you've used dataType: "json"
. From jQuery docs:
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
You don't need to call var status = JSON.parse(data);
. Just use data
as you'd use result of JSON.parse
.
Also if your server return json content type, then jQuery will choose dataType
to be "json"
. From docs:
If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Upvotes: 2