- The download link for json2.js is available from github :-
- Lets understand what is there inside the Crockford json2.js. There are only two methods present that can be used by a java script developer to use in their code to parse a String to a JSON format or vice versa.
JSON.stringify(value, replacer, space)
JSON.parse(text, reviver)
-
Example,
JSON.stringify({name: "Sandeep Patel", class: "10th"});
Output: '{"name":"Sandeep Patel","class":"10th"}' //output as Strong
JSON.parse('{"name":"Sandeep Patel","class":"10th"}');
Output:{name: "Sandeep Patel", class: "10th"} //output as java script object
-
Inside JSON2.js,
--> If You Look into the beginning of the code one can see the following code,
if (typeof JSON !== ‘object’) {JSON = {};}
These lines are for checking whether the object “JSON” is already available or not.These lines provides safety from overriding the existing JSON object.At present some of the browser like Mozilla in their current version already have an JSON implementation.So this line is helpful when a browser does not have an implementation for JSON then it creates an object for supporting JSON parsing.--> Then these lines,
if (typeof Date.prototype.toJSON !== ‘function’) {Date.prototype.toJSON = function (key) {return isFinite(this.valueOf()) ? this.getUTCFullYear() + ‘-‘ +f(this.getUTCMonth() + 1) + ‘-‘ +f(this.getUTCDate()) + ‘T’ +f(this.getUTCHours()) + ‘:’ +f(this.getUTCMinutes()) + ‘:’ +f(this.getUTCSeconds()) + ‘Z’: null;};These lines checks whether the current browser’s Date Object has already have method called toJSON. If not, then it adds a method to it.The purpose of this method is converting a date format to UTC json format.example,var d = new Date();console.log(d.toJSON()) // Output 2012-11-13T18:02:12.296Z
--> Then the lines ,
if (typeof JSON.stringify !== ‘function’) {JSON.stringify = function (value, replacer, space) {……..…….}These lines are similarly checks for stringfy meethod is present or not in JSON object.If not then it creates that method and declared the definitions for it.--> Then again these lines,
if (typeof JSON.parse !== ‘function’) {JSON.parse = function (text, reviver) {…..…..}Similar to other methods.It takes the strings and return its json format.
If athe input String is wrong the it throws a Syntax error exception.
throw new SyntaxError('JSON.parse');
Interanally a eval() function does the work to convert the string toappropiate JSON object .it does its work with a safe manner.
It uses a reviver function called walk.
This walk function iterate over the key value pair and checks for
hasOwnProperty method to determine which are the properties belongs to the
objects and escaping function and other predefined objects.
function walk(holder, key) {var k, v, value = holder[key];if (value && typeof value === ‘object’) {for (k in value) {if (Object.prototype.hasOwnProperty.call(value, k)) {v = walk(value, k);if (v !== undefined) {value[k] = v;} else {delete value[k];……..……….