Sunday 24 September 2017

Handling JSON with jQuery



  • JSON (JavaScript Object Notation) is a way to store information in an organized manner.
  • It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML.
  • This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML.
  • JSON returned via REST APIs is used in different ways on the client side.
     
  • You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. 


Format JSON in jQuery


  • Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can’t be displayed directly on the UI.
  • There are different ways to format it. Either using your own implementation or third-party plugins. 

Formatting the JSON using jQuery can be done easily and requires only 2 function calls:

1) JSON.parse() / jQuery.parseJSON() – To parse a JSON string and convert it to a JavaScript object.

2) JSON.stringify() – Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats a JSON string:

Example:-
var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
'{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' +
'{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
'{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var tmpData = JSON.parse(jData);
var formattedJson = JSON.stringify(tmpData, null, '\t');

Here, the formattedJson variable will have the formatted JSON string, indented using tab.
To display formatted JSON on UI, use the <pre> tag only. If you want to display inside a div, you would need to first append the <pre> tag in the div element.

example:- :$('#dvText').append($('<pre>').text(formattedJson));

jQuery.parseJSON vs JSON.parse


  • JSON.parse() and jQuery.parseJSON(), both are used to parse a JSON string and returns resulting JavaScript value or object described by the string.
  • jQuery.parseJSON() is available only when jQuery library is used where JSON.parse() is JavaScript’s standard built-in JSON object method. 

So the question is if jQuery library is used, then which one should be used or both gives same performance and result?

Well, the answer is that both are equal. As you know, jQuery’s library is written on top of JavaScript.
So  jQuery.parseJSON() makes use of JSON.parse() internally.

Here is the code of jQuery.parseJSON() method from jQuery 1.9.1 library.
As you can see, it first checks if JSON.parse is supported or not.
If supported, then it makes use of JSON.parse only. Otherwise, it tries to evaluate string data with new Function.

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

if (data === null) {
    return data;
}

if (typeof data === "string") {
    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim(data);
    if (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);
}

This was done as JSON.parse is natively available on some browsers, and jQuery is browser independent. So if JSON.parse is not available, then it falls back to jQuery implementation.

JSON.parse was not supported in old browsers like IE 7 and Safari 3, but over the period of time, browsers have also evolved. And now most of the browsers support JSON.parse. Therefore, the implementation of jQuery.parseJSON() is also changed after jQuery 2.0 release.
Here is the code of new implementation from jQuery 2.2.4 library:

// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function(data) {
    return JSON.parse(data + "");
};

And the big news is that with jQuery 3.0, jQuery.parseJSON is deprecated. So now to parse JSON objects, use the native JSON.parse method instead.

No comments:

Post a Comment