user972946
user972946

Reputation:

Why jQuery.parseJSON does not parse this valid JSON document in Firefox?

Server returns this JSON document:

{
"username-found": true,
"question-required": true
}

Which successfully passes JSONLint's validity check.

In web browser:

$.post('my_url', {"post":"data"}, function(data) {
  data = $.parseJSON(data);
});

The code runs and successfully parses the JSON document in Opera 12 browser, however in Firefox 16, JavaScript error occurs and says "not well-formed".

JQuery is of version 1.7.2.

I cannot see what I did wrong there, do you know?

Edit:

Does it have anything to do with the way server returns the JSON? Here it is:

return new StreamingResolution("text", new StringReader(json.toString()));

uggestion, I might have found the cause. When I did alert(data), Firefox tells me that data is an object, Opera tells me that data is the JSON string.

Upvotes: 2

Views: 5447

Answers (3)

Marc
Marc

Reputation: 6771

Solution 1 (Client) - Set DataType in jQuery Request

I think the internals are a bit different in that specific browser version (because jQuery tries to detect the dataType automatically and is doing the parsing internally in the case of a JSON response) and JSON is automatically encoded in FF and not in Opera?

Try to add the dataType so jQuery will handle this (I would prefer that):

$.post('my_url', {"post":"data"}, function(data) {
    // data should be an json object here
}, 'json');

It's just a guess.

OR Solution 2 (Server) - Send MIME type

You could also send a correct MIME type from the server so you don't have to set the dataType on the client. Its up to you but I think that would be the correct solution.

Regarding this answer it should be application/json.

Reference

How is the dataType detected automatically in jQuery?

Default: Intelligent Guess (xml, json, script, or html) The type of data that you're expecting back from the server. 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).

Source: http://api.jquery.com/jQuery.ajax/

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55750

You can directly use the data object directly ..

No need to use $.parseJSON();

Upvotes: 1

edrian
edrian

Reputation: 4531

You also have a $.getJSON shortcut method in jQuery. Maybe jQuery automatically uses the best configuration for this case and maybe start working

Here is the $.getJSON documentation

Upvotes: 0

Related Questions