Zhaiduo
Zhaiduo

Reputation: 49

Get json object without JSON.parse?

I found this:

Use Python output:

print ‘Content-type: text/x-json\n\n’
print json.dumps([{'title':arr['title']}])

and get json string with Jquery:

$ajax(   
   success: function(msg){
      if(msg[0].title) alert(msg[0].title);
   }
)

It works, who can tell me why it is? Thanks~

Upvotes: 1

Views: 1598

Answers (3)

meder omuraliev
meder omuraliev

Reputation: 186562

jQuery calls JSON.parse internally on modern browsers that have it if the Content-Type is json

        return window.JSON && window.JSON.parse ?
            window.JSON.parse( data ) :
            (new Function("return " + data))();

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630389

If you set the dataType to "json" or you don't set it and the content-type header contains the string "json", it tries to parse it, you can see the logic at work here:

if ( typeof data === "string" ) {
  // Get the JavaScript object, if JSON is used.
  if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
    data = jQuery.parseJSON( data );

  // If the type is "script", eval it in global context
  } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
    jQuery.globalEval( data );
  }
}

If you're curious, the source for jQuery.parseJSON() is here.

Upvotes: 1

Chris Gutierrez
Chris Gutierrez

Reputation: 4755

I believe jQuery is able to determine the response type based on the header you are sending and automatically evaluate it as JSON.

Upvotes: 1

Related Questions