¿Por qué no es necesario 'jQuery.parseJSON'?

i'm doing an ajax request with query and wondering why my response is already a JS object.

Si hago un

var obj = jQuery.parseJSON(response);

'obj' is null, but i can use 'response' as an array of js objects.

This is not really a problem, but i would like to understand this behavior.

Muchas Gracias

preguntado el 02 de febrero de 12 a las 11:02

5 Respuestas

This happens when you make an AJAX call and specify the dataType JSON jQuery calls jQuery.parseJSON on the response for you. In fact you can specify what function to call depending on the dataType as you can se from the documentación

converters(added 1.5)
Map Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response

So if you make a call like this

$.ajax({
  url: yoururl,
  dataType: "json",
  success: function(data){
    //data is already a json
  }

If you don't specify a dataType jQuery tries to guess it

dataTypeString 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). The available types (and the result passed as the first argument to your success callback) are:

"xml": Devuelve un documento XML que se puede procesar a través de jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests. "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string. multiple, space-separated values:
As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

Respondido 02 Feb 12, 15:02

additionally, the server can also set the Content-Type encabezado a application/json, and jQuery will mejor conjetura the response format. - Matt

"of course you must set the correct headers server side" is incorrect. jQuery fideicomisos lo que pones dataType to. It only checks the headers if it has to mejor conjetura. - Matt

It pretty much depends which dataType you pass into your jQuery ajax request. This might happen implict by calling .getJSON() o directamente usando $.ajax().

However, if you omit the dataType, jQuery trys to do some magic and guesses which data was received. As for JSON data, it uses a simple regular expression to check if a response looks like a JSON-string and if so, it automatically parses it for you. jQuery will try to infer it based on the MIME type of the response.

So always be precise and tell jQuery which type of data you expect.

Respondido 02 Feb 12, 15:02

It simply checks content-type header or overriden mimetype, there is no parsing of the response content to see what type it is - Esailija

@Esailija: true fixed that. I was confused about the validation regexp parseJSON uses internally. - jAndy

The default behaviour of jQuery's ajax method is to analyse the response and return it as the most appropriate data type. If your response looks like JSON, therefore, it will be converted to a JavaScript object/array.

You can override this behaviour by setting the dataType attribute in the ajax settings.

Respondido 02 Feb 12, 15:02

si especifica el dataType as json the jquery parses the response for you like

$.ajax({
...
dataType:'json',
...
});

same is the case with jQuery.getJSON ()

this is how the source code for getJSON se ve

getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},

https://github.com/jquery/jquery/blob/master/src/ajax.js#L283

Respondido 02 Feb 12, 15:02

Porque

jQuery.ajaxSettings.converters["text json"] === jQuery.parseJSON

I.E it will run the function everytime json response is detected automatically or explicitly set by yourself

Respondido 02 Feb 12, 15:02

This is not "la razón" why the object is returned. This makes it posible for the object to be returned (as there is now a converter from * -> text y entonces text -> json), but it's the dataType or best-guess which actually does the conversion. - Matt

@Matt Yes it is, if you make that function return "hello", all responses detected json will return "hello" to you. I am using this to preprocess for(;;); out of all responses. - Esailija

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.