Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 595
Jordan Avatar asked Jan 01 '14 17:01

Jordan


People also ask

How can you parse JSON via jQuery?

JQuery | parseJSON() method This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value. Parameters: The parseXML() method accepts only one parameter that is mentioned above and described below: json: This parameter is the well-formed JSON string to be parsed.

How can I convert JSON to string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How display JSON data in HTML using jQuery?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


1 Answers

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

like image 50
Lix Avatar answered Sep 28 '22 07:09

Lix