0

i want to save a Json file and save all of data and functions.

i use JSONfn, but still doesn't give me Functions.

i already try this code but it doesn't work as i want:


fs.writeFile("object.json", JSON.stringify(track)), "utf8");

it give's full object of data but, i need functions too.

  • Json itself doesn't support that. So the quick answer is no. I wonder if its possible to stringify functions to plain text – Rashomon Apr 12 '19 at 17:27
  • 1
    Explain your use case because the short answer is no if you are wanting to create functions from that again, but there may be other approaches to solve your higher level issue depending on what you are wanting to accomplish – charlietfl Apr 12 '19 at 17:30
  • i just want to save and see the functions , it doesn't matter json or other formats – Parsa Radfar Apr 12 '19 at 17:31
  • 2
    *"save and see functions"* is far too vague and this is an [XY Problem](http://xyproblem.info/) – charlietfl Apr 12 '19 at 17:33
  • is there any way to see the functions? no matter in String – Parsa Radfar Apr 12 '19 at 17:42
  • Can you tell us what you are exactly trying to achieve ( X ) by stringifying an object that also has methods and primitive values alike ( Y ) – Jibin Joseph Apr 12 '19 at 17:45

1 Answers1

0

JSON.stringify() takes a replacer parameter, which maybe a function. It takes two params which denote the key and the value. You check if its a function, and accordingly turn it into a string.

const track = {
  variable: 2,
  something: (pass) => {
    console.log(pass)
  } 
}

const string = JSON.stringify(track, (k,v) => {
      if(typeof v === "function"){
        return v.toString(); 
      }
    return v;
})

console.log('string',string)
Jibin Joseph
  • 1,265
  • 7
  • 13