JSON.parse() and JSON.stringify()
JSON.stringify() and JSON.parse() are two useful tools for handling JSON-formatted content in JavaScript
JSON.stringify()
//SYNTAX JSON.stringify(value[, replacer[, space]])
The JSON.stringify()
method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
console.log(JSON.stringify({ age: 25, height: 166, weight:65 })); // expected output: "{"age":25,"height":166,"weight":65}"
const employee = { id: 117, name: "Anand", email: "me@anand.com" }; function replacer(key, value) { if (typeof value === "number") { return value * 2; } if (key === "email") { return "Emails are masked."; } return value; } console.log(JSON.stringify(employee)); // result: {"id":117,"name":"Anand","email":"me@anand.com"} console.log(JSON.stringify(employee, replacer)); // {"name":"Anand","email":"Emails are masked."} console.log(JSON.stringify(employee, null, "^_^ ")); // result: { // ^_^ "id": 117, // ^_^ "name": "Anand", // ^_^ "email": "me@anand.com" // } console.log(JSON.parse(JSON.stringify(employee))); // result: Object {id: 117, name: "Anand", email: "me@anand.com"}
JSON.parse()
//SYNTAX JSON.parse(text[, reviver])
The JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string.
An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
var json = '{"name":"Anand", "id":117}'; obj = JSON.parse(json); console.log(obj.name); // expected output: Anand console.log(obj.id); // expected output: 117
If the reviver
parameter is specified, the parsed value is transformed before being returned. If the reviver
only transforms some values and not others, you should make sure you return all untransformed values as-is, otherwise they will be deleted from the resulting object.
JSON.parse('{"Age": 15}', (key, value) => { console.log(key); // log the current property name". return value * 3; // return value * 3 }); // Age // { Age: 45 }