Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

JSON.parse() vs JSON.stringify()


//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);

 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
5+9 =