DEV Community

Cover image for Did You Know JSON.stringify() Eat This Specific Value
Fahim Zada
Fahim Zada

Posted on

Did You Know JSON.stringify() Eat This Specific Value

Hi there,
Have you ever encountered a situation when trying to convert an object containing a function as a value to a string using JSON.stringify()? and noticed by printing the resultant value that the key containing the function value is gone along with its key?

Well, that is because JSON.stringify() marks it null. It can not convert a function value to a string, thus keeping it null. Now your whole object is changed. Here is an example if you don't know how to include it or convert it back to function.

const obj = {
  author: "Fahim Zada",
  love: "0's and 1's",
  eat: () => console.log("Red Apple")
}

console.log(JSON.stringify(obj)) 
//"{'author':'Fahim Zada','love':'0's and 1's'}"
//Let us try to fix it by converting that key to string
obj.eat = obj.eat.toString()
console.log(JSON.stringify(obj))
//"{'author':'Fahim Zada','love':'0's and 1's','eat':'() => console.log(\'Red Apple\')'}"

//Converting back to js object 
const stringify = JSON.stringify(obj)
const convert = JSON.parse(stringify)
//Now you can access primitive values as normal
console.log(convert.author) 
//"Fahim Zada"
//For our function, we will do this with "new" keyword or without
//Invoking the function with ()
//Will return our function and now we can call it
const myFunc = new Function("return " + convert.eat)()
console.log(myFunc())
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

Top comments (3)

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi Fahim,
You might be interested to know (if you don't already) that JSON.parser and JSON.stringify take a second argument (reviver and replacer respectively.) The second parameter provide functions that could help perform the string/function conversions, you illustrated in you post, during the parse/stringify operations.
In fact the JSON.stringify method can take three arguments with the third being the number of spaces to be used to indent each property in the string.
However, using the Function constructor function (like eval) is widely regarded as being hazardous and should be avoided.
My Best Regards

Collapse
 
itsfz1 profile image
Fahim Zada

Hi TGJ,
We use replacer mostly when we have to replace multiple keys based on a condition. This code is a simple example. I didn't mention the replacer and spacer, nor did I use them because I wanted to keep the post simple and focused.
Yes, that's why I didn't use eval().
Thanks to you, the post is now fully complete.
Best Regards

Collapse
 
fyodorio profile image
Fyodor

That’s totally reasonable, as JSON was invented for storing/transferring data, not modifying it πŸ€·β€β™‚οΈ