jQuery load/parse JSON response

jQuery load/parse JSON response

jQuery.parseJSON( json );

Takes a well-formed JSON string and returns the resulting JavaScript value, probably object or array of objects. Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

  • “{test: 1}” (test does not have double quotes around it).
  • “{‘test’: 1}” (‘test’ is using single quotes instead of double quotes).

Note that JSON syntax is stricter, JSON insists that property names be quoted with double-quote characters, and of course values can only be numbers, strings, booleans, or null.

var str = '{"val1": 1, "val2": 2, "val3": 3}';
var obj = jQuery.parseJSON( str );

So, what if you get JSON array as response.

var str = '[{"val1": 1, "val2": 2, "val3": 3},{"val4": 4, "val5": 5, "val6": 6}]';
var obj = jQuery.parseJSON( str );

This time variable obj will hold reference to array of objects.

If jQuery has provided such a simple solution, then what the heck is this:

jQuery.getJSON( url, [data], [callback] );

The method returns XMLHttpRequest object. In addition to parsing, this method loads JSON data. It’s more of a client service with some useful functions.

  • url − A string containing the URL to which the request is sent
  • data − This optional parameter represents key/value pairs that will be sent to the server
  • callback − This optional parameter represents a function to be executed whenever the data is loaded successfully

Assuming we have following JSON content in anoop.json file −

"name": "Anoop Rai",
"blood_group" : "O+",
"city": "Noida"
jQuery.getJSON('anoop.json', function(jd) {

Thats nice, it not only loaded data, but it also parsed that data for you. getJSON is shorthand for parsing a response text from an AJAX request as JSON. When you call getJSON, you’re actually performing an asynchronous request. It actually issues a HTTP GET request to the server and executes a callback when the data is received. In otrher words jQuery.getJSON() method loads the JSON-encoded data from the server using a GET HTTP request based on a URL to which the request is sent. You may then choose to use jQuery.parseJSON() method to parse the JavaScript object or array as defined by the JSON structure.

Leave a Reply

Your email address will not be published. Required fields are marked *