Basic Guide, Properties and Usecases of JSON (JavaScript Object Notation)
JSON Methods

The global variable JSON serves as a namespace for functions that produce and parse strings with JSON data.

So the two main methods associated with JSON namesake are:

Stringify Parse

JSON.stringify(value, replacer?, space?)

It is a method on JSON which produces the strings with JSON data.

It translates the JavaScript value value to a string in JSON format.It has 2 optional arguments : replacer and space.

The optional parameter replacer is used to change the value before stringifying it. For example:

replacer function

Using the replacer:

> JSON.stringify({ a: 5, b: [ 2, 8 ] }, replacer)

'{"a":10,"b":[4,16]}'

The optional parameter space influences the formatting of the output. Without this param, the stringified value will be a single line of text.:

> console.log(JSON.stringify({a: 0, b: ['

']}))

{"a":0,"b":["

"]} > console.log(JSON.stringify({a: 0, b: ['

']}, null, 2))

{

"a": 0,

"b": [

"

"

]

} > console.log(JSON.stringify({a: 0, b: ['

']}, null, '|--'))

{

|--"a": 0,

|--"b": [

|--|--"

"

|--]

}

Two Data Ignored by JSON.stringify()

If the value is a function, then the JSON.stringify() ignores it.

eg:

a) var obj = {

“name”: “Rahul”,

“describe”: function(){return 10;}

}

> JSON.stringify(obj)

‘{“name”: “Rahul”}’ ;i.e., the function is ignored

b) JSON.stringify() handles values that are not supported by JSON (such as functions and undefined)

> JSON.stringify(function() {})

undefined

The toJSON() Method

If JSON.stringify() encounters an object that has a toJSON method, it uses that method to obtain a value to be stringified. For example:

> JSON.stringify({ toJSON: function () { return 'Cool' } })

'"Cool"'

Dates already have a toJSON method that produces an ISO 8601 date string:

> JSON.stringify(new Date('2011-07-29'))

'"2011-07-28T22:00:00.000Z"'

JSON.parse(text, reviver?)

It parses the JSON data in text and returns a JavaScript value. Here are some examples:

> JSON.parse("'String'") // illegal quotes

SyntaxError: Unexpected token ILLEGAL

> JSON.parse('"String"')

'String'

> JSON.parse('123')

123

> JSON.parse('[1, 2, 3]')

[ 1, 2, 3 ]

> JSON.parse('{ "hello": 123, "world": 456 }')

{ hello: 123, world: 456 }

The optional parameter ‘reviewer’ can be used to transform the parsed data.

In this example, we are translating date strings to date objects:

dateReviewer function

The result is:

> var str = ‘{ “name”: “Rahul”, “birth”: “1998–05–15T22:00:00.000Z” }’;

> JSON.parse(str, dateReviver)

{ name: ‘Rahul’, birth:“Fri, 15 May 1998 22:00:00 GMT” }
['Rahul Mahajan']
['JavaScript', 'Json Stringify', 'Json Parse', 'Json']