Turn function into String with Javascript

Asked

Viewed 97 times

-1

Assuming I have the following object below

const teste  = {
  onload:  ()=> {
    console.log('a')
  }
}

Where the onload attribute is a function, and I need it to be transformed into a string so that I can use it in another place by passing it back to object, but I do:

console.log(JSON.stringify(teste)) 

I have as a result {}

It would have some way to convert every object including the functions in it, into a string?

  • Why do you need to convert it into a string? It wouldn’t be easier to send the function reference?

1 answer

0


You can use the second argument from JSON.stringify, to pass a function of replace, that allows you to modify the way data is "serialized":

const obj = {
  onload: () => console.log("Foo")
};

const json = JSON.stringify(
  obj,
  (name, val) => typeof val === 'function'
    ? val.toString()
    : val
);

console.log(json);

We are also using the method Function.prototype.toString.

But to do this does not seem like a good idea, especially if this type of data is passed into the hands of a user. In addition, you will be using JSON to transfer data that it was not made to work - functions. There are probably other better ways to do what you need.

  • And how to switch back to Json elsewhere? , I tried JSON.parse and it returns me {onload: "() => console.log("Foo")"}

  • I tested here and json is valid. Only the function will be converted to string, not function. You will have to use eval or new Function to turn it back into a function. That is why this approach is in fact insecure and perhaps it is better to reconsider using it.

  • Blz, thank you so much for the explanation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.