-3

I have a requirement where I convert a function that is in JSON to a JS object. How can I do that? For example,

If I have the JSON object like:

{"obj":{ "a": "abc", "b": "(v) => { console.log('Hi', v) }" } }

Then I want the above JSON to convert it back to the original object:

const obj = { a: 'abc', b: (v) => { console.log('Hi', v) } }

Is this possible? And can it be done without using eval?

Currently when I do stringify & parse the function is getting ignored

Also I want to add that I want to construct the desired JS object but not actually evaluate/run the function.

  • You say you'd like to avoid `eval`, but you want to evaluate an arbitrary string as code right? What's wrong with eval here? Maybe this helps? https://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript – CollinD Jun 07 '22 at 21:29
  • @CollinD Thank you for the response. I was just trying to see if I can just construct the desired object but not actually evaluate or run the function – kartik gavara Jun 07 '22 at 21:35
  • Hi plichard, Like I mentioned in the question. I dont want to log the console statement or run the function, but simply construct the JS object with the function. I want to convert {"obj":{ "a": "abc", "b": "(v) => { console.log('Hi') }" } }(JSON) to const obj = { a: 'abc', b: (v) => { console.log('Hi') } } (JS object) – kartik gavara Jun 07 '22 at 22:10

1 Answers1

1

This is how I would do it using new Function(argument,function_body)

const json = '{"obj":{ "a": "abc", "b": "console.log(\'Hi\')" } }'
const data = JSON.parse(json);
var f = new Function(data.obj.a,data.obj.b);
f();
Lucas Roquilly
  • 406
  • 2
  • 9
  • Hi Lucas, Like I mentioned in the question. I dont want to log the console statement, but simply construct the JS object with the function. I want to convert {"obj":{ "a": "abc", "b": "(v) => { console.log('Hi') }" } }(JSON) to const obj = { a: 'abc', b: (v) => { console.log('Hi') } } (JS object) – kartik gavara Jun 07 '22 at 22:09
  • Hi Kartik, well in my snippet the JS object is the `data` variable – Lucas Roquilly Jun 07 '22 at 22:19
  • In my usecase, i have an anonymous function like i showed in the example which also takes in some arguments. So, is that something that is possible? – kartik gavara Jun 07 '22 at 22:26