0

completely beginner here. I have the jquery library. I make a call to an api that returns json. i would like to use the parseJSON function within the jquery library to parse it. simply put, i have no idea how to do so.

I can find the function within the jquery library, it looks like so:

parseJSON: function( data ) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim( data );

    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if ( rvalidchars.test( data.replace( rvalidescape, "@" )
        .replace( rvalidtokens, "]" )
        .replace( rvalidbraces, "")) ) {

        return ( new Function( "return " + data ) )();

    }
    jQuery.error( "Invalid JSON: " + data );
},

How do i send my json through that?

0

4 Answers 4

2
var obj = jQuery.parseJSON(yourJsonObj);
Sign up to request clarification or add additional context in comments.

Comments

2

If you are using the jQuery AJAX commands, most of them take a dataType parameter. Setting dataType to 'json' will automatically parse the returned data.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

In this case data will end up being an object based on the JSON returned from the AJAX call.

Comments

1

If you use the jQuery.getJSON function, you can access your API endpoint and have the response parsed all in one call.

$.getJSON("/my_resource.json", function(data) {
  // Use data here
});

Comments

0

jQuery's parseJSON() function will convert the json to a javascript object.

if your json is, for example:

{ "firstname" : "john", "lastname" : "doe" }

then when you use parseJSON, you can access the properties like so:

var json = '{ "firstname" : "john", "lastname" : "doe" }';
var person = jQuery.parseJSON(json);

console.log(person.firstname); //will show john
console.log(person.lastname); //will show doe

that should get you started. for more, read the doc here: http://api.jquery.com/jQuery.parseJSON/

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.