Tuesday, 13 February 2018

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

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()?
var objectData={}
objectData.a='Apple';
objectData.b=undefined;
objectData.c=';
   
objectData=JSON.stringify(objectData, function(k, v) {                
if (typeof v === 'undefined') {
  return '';
}else{
    return v;
}
});

this replacer function will replace the undefined with empty space.




Question: Give an example of array of replacer of JSON.stringify()?
var foo = {name: 'web tech', week: 350, transport: 'car', month: 7};
JSON.stringify(foo, ['week', 'month']);  //"{"week":350,"month":7}"

IT will return those which match with array




Question: Difference between JSON.stringify and JSON.parse?
JSON.stringify convert a Javascript object into JSON text(JOSN string).
JSON.parse convert a JSON text into into Javascript object.

Both are opposite to each other.