/*
JSON.stringify() takes a JavaScript object and then transforms it into a JSON string.
JSON.parse() takes a JSON string and then transforms it into a JavaScript object.
*/
const myObject = {
dog: "dog",
cat: "cat",
koala: "koala",
count: 3
};
console.log(JSON.stringify(myObject));
// result: {"dog":"dog","cat":"cat","koala":"koala","count":3}
console.log(JSON.parse(JSON.stringify(myObject)));
// result: Object {dog: "dog", cat: "cat", koala: "koala", count: 3}
//How To Use JSON.parse() and JSON.stringify()
//JSON.parse() takes a JSON string and transforms it into a JavaScript object.
let userStr = '{"name":"Sammy","email":"sammy@example.com","plan":"Pro"}';
let userObj = JSON.parse(userStr);
console.log(userObj);
/* JSON.parse() can take a function as a second argument that can transform the object values before they are returned.
Here the object’s values are transformed to uppercase in the returned object of the parse method: */
let userStr2 = '{"name":"Sammy","email":"sammy@example.com","plan":"Pro"}';
let userObj2 = JSON.parse(userStr2, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(userObj2);
console.log("
");
/* JSON.stringify() takes a JavaScript object and transforms it into a JSON string. */
let userObj3 = {
name: "Sammy",
email: "sammy@example.com",
plan: "Pro"
};
let userStr3 = JSON.stringify(userObj3);
console.log(userStr3);
parse() takes a JSON string and transforms it into a JavaScript object. JSON. stringify() takes a JavaScript object and transforms it into a JSON string.