JavaScript JSON

The JSON (JavaScript Object Notation) is a general format to represent values and objects. JSON is the string form of object.

Syntax:


JSON.stringify(value[, replacer[, space]])

Parameters:

Value
The value to convert to a JSON string.

Replacer Optional
The replacer parameter can be either a function or an array that fliter the entire object.

Space Optional
The space argument may be used to control spacing in the final string.

In JavaScript We have two method:

JSON.stringify to convert objects into JSON.
JSON.parse to convert JSON back into an object.


var user = {
	name: "XYZ",
	age: 30
};

var json = JSON.stringify(user);

console.info(typeof json); // string

How to JSON works with other data type



// a number in JSON is just a number
console.info( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
console.info( JSON.stringify('test') ) // "test"

console.info( JSON.stringify(true) ); // true

console.info( JSON.stringify([1, 2, 3]) ); // [1,2,3]

Replacer



var user = {
	name: "XYZ",
	age: 30
};

var json = JSON.stringify(user, ['name']);

console.info(json); // {"name":"XYZ"}


Space


var user = {
	name: "XYZ",
	age: 30
};

var json = JSON.stringify(user, ['name', 'age'], '\t');

console.info(json); 

{
	"name": "XYZ",
	"age": 30
}

About the Author: Pankaj Bisht