JSON.stringify() is method by which you can convert javascript object or array in JSON string.
Is JSON.stringify methods takes only one parameter? The answer is NO.
syntax : JSON.stringify(value, replacer, space)
What is value? Which can be array or object.
Mostly we used this single parameter.But remaining two parameters are also important.
What is replacer? Replacer can be function or array we can use it according to our needs.
By using replacer function we can modify key value pairs before final output.
Here replacer function takes two arguments one is key and another is value.
Let's see example:
const student = {
name: "Shubham",
email: "shubham123@gmail.com",
password: "shubham1234"
}
function replacer(key, value) {
if (key === "password") {
return undefined;
}
else if (key === "email") {
return "shubham1122@gmail.com"
}
else {
return value
}
}
const jsonObj = JSON.stringify(student, replacer, 10)
console.log(jsonObj)
OUTPUT-
{
"name": "Shubham",
"email": "shubham1122@gmail.com"
}
We know that stringify function only return values which are not undefined. That's why in final output password key is not present.
replacer act as array which specifies which key value pairs should display in final output
const student = {
name: "Shubham",
email: "shubham123@gmail.com",
password: "shubham1234"
}
const replacer = ["name", "email"]
const jsonObj = JSON.stringify(student, replacer, 10)
console.log(jsonObj)
OUTPUT-
{
"name": "Shubham",
"email": "shubham123@gmail.com"
}
This parameter usually null if we don't want any changes in final output.
Last parameter is space which specifies indentation space which improves the readability which can be maximum 10.
JSON.parse() method is used to convert JSON string into object or array.
JSON.parse() method takes two parameters.
Syntax-JSON.parse(string, reviver)
Means first parameter is JSON string but we are not aware about second parameter.
Because second parameter is optional but what it does?
This is a function which is used to transform actual key value pairs before final output. This function takes two arguments one is key and another is value and this function will apply on each key value pair.
Ex:
const user = `{
"name": "Shubham",
"age":25,
"location":"Pune"
}`
const reviver = (key, value) => {
if (typeof (value) === 'number') {
return value * 2
}
else {
return value;
}
}
const result = JSON.parse(user, reviver)
console.log(result)
OUTPUT-{name: 'Shubham', age: 50, location: 'Pune'}
Top comments (0)