6

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.

2
  • What response are you getting from the get() request? The response is what you'll want to convert into a JSON. Commented Jan 1, 2014 at 17:20
  • @Lix, I'm requesting this page roblox.com/catalog/… Commented Jan 1, 2014 at 17:20

2 Answers 2

3

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 ] )

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.