-2

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.

3
  • 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? stackoverflow.com/questions/7650071/… Commented Jun 7, 2022 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 Commented Jun 7, 2022 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) Commented Jun 7, 2022 at 22:10

1 Answer 1

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();

Sign up to request clarification or add additional context in comments.

3 Comments

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)
Hi Kartik, well in my snippet the JS object is the data variable
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.