-1

I've been trying to save a self contained javascript object to JSON, but when using eval or JSON.parse() it gets rid of the anonymous function

let test = '({"a":1000, "b":()=>{return console.log("hello");}})';

test = eval(test);

console.log(test);

Output:

[LOG]: {
"a": 1000
}

I'm making an API and I would like to export the whole object including the function, is it possible to export the raw code even if it's not a JSON per se?

Thank you in advance

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Kyle
  • 1,568
  • 2
  • 20
  • 46
  • 3
    JSON does not have functions – epascarello Aug 16 '22 at 16:32
  • 1
    Your example code doesn't use JSON at all. (Your example works, `b` in the reconstituted object is a function.) And as @epascarello said, JSON doesn't have functions. It's a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) – T.J. Crowder Aug 16 '22 at 16:35
  • 1
    JSON is good for data, but not really for objects. It sounds like you really want serialization of your object. Never done that in JS myself, but it's common in other languages. Probably find good stuff out there if you look... – pixelearth Aug 16 '22 at 16:36
  • *"is it possible to export the raw code even if it's not a JSON per se?"* Yes, usually. You did that in your initial code snippet. That successfully makes a round-trip through text. – T.J. Crowder Aug 16 '22 at 16:37
  • 1
    https://stackoverflow.com/questions/7395686/how-can-i-serialize-a-function-in-javascript – CrayonViolent Aug 16 '22 at 16:42
  • APIs are intended to be language-agnostic. It makes no sense to have a function in an API parameter or result, since the receiver may not be in the same language. – Barmar Aug 16 '22 at 16:43
  • 1
    [It can be done.](https://stackoverflow.com/questions/40875630/javascript-save-object-with-methods-as-a-string/40876342#40876342) – Scott Marcus Aug 16 '22 at 16:48

1 Answers1

-1

I've finally figured it out, thank you everyone

let test = '({"a":1000, "b": ()=>{return console.log("hello");}})';
    let code = test.toString();
    let coder = eval(code);
    coder.b();
Kyle
  • 1,568
  • 2
  • 20
  • 46