Jordan
Jordan

Reputation: 495

Converting JSON using jQuery

For reference, this is the JSON I'm working with: http://goo.gl/xxHci0

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.

Upvotes: 6

Views: 132

Answers (2)

Spikeh
Spikeh

Reputation: 3695

You can use getJson. This converts your JSON string to a JavaScript object.

I threw JSFiddle together for you using the facebook graph api:

http://jsfiddle.net/J4LCX/

$.getJSON( "http://graph.facebook.com/spikeh/",
    function( data ) {
        alert(data.id);
    });

Alternatively, to fix your code, just reference the object's id directly:

$.get (
    "http://graph.facebook.com/spikeh/",
    function parse(data) {
        alert(data.id);
    }
);

JsFiddle: http://jsfiddle.net/LBy9y/

Upvotes: 0

Lix
Lix

Reputation: 47956

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:

  • $.get()

    jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

Upvotes: 3

Related Questions