Tuesday, 13 February 2018

JSON.stringify - What is JSON.stringify? and how to use?

Question: What is JSON.stringify()?
The JSON.stringify() method converts a JavaScript value to a JSON string.
It can also convert a Object/Array to JSON String.

Question: Give few example of JSON.stringify()?Following are few example of JSON.stringify()

JSON.stringify({}); // {}

JSON.stringify(true); // 'true'

JSON.stringify('foo'); // '"foo"'

JSON.stringify([1, 'false', false]); // '[1,"false",false]'

JSON.stringify({ x: 5 }); // '{"x":5}'

JSON.stringify({ x: 5, y: 6 });// '{"x":5,"y":6}'

JSON.stringify({ x: 5, y: 6 });// '{"x":5,"y":6}'

Question: What is use of 2nd parameter of JSON.stringify()?
2nd parameter of JSON.stringify() is a replacer.
It can be an array OR can be function.Question: Give an example of callback function of replacer of JSON.stringify()?