javascriptjqueryjsonget

Converting JSON using jQuery


In regular JavaScript, using the code below works fine and I can manipulate it easily:

var info = JSON.parse(document.getElementsByTagName("pre")[0].innerHTML);
alert(info[0]["AssetId"]);

But I'm working on a jQuery version of the same code to avoid using methods like iFrames to get this data. My jQuery function is:

$.get (
    page,
    function parse(data) {
        var r = $.parseJSON(data);
        alert(r[0]["AssetId"]);
    }
);

I found ways to convert the JSON using jQuery, but I'm having trouble finding where the JSON code is that needs to be converted.


Solution

  • Provided that the response from the server is a valid string representation of a JSON object, you'll be able to specify the dataType for the get() request. You could do something like this:

    $.get( page, function( data ) {
      alert( data[0]["AssetId"] );
    }, "json" ); // <-- here is the dataType
    

    With the correct dataType set, you will not need to manually parse the data, it will arrive in your callback function as a JSON object.

    References: