I have a json string like this:
json = "{'run': 'function() { console.log('running...'); }'}"
How do I run that function inside of the json string?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’re going to have to use the
eval()(doc) function. A lot of people have a lot of feelings about this function. JSON is best for transporting data, not functions (see JSON). The functions ought to lay in the script on the page.Also there’s a syntax error in your posted code (function is wrapped in single quotes (‘), and so is console.log’s first parameter).
But…
Update:
Oh, and I was mistaken. Eval doesn’t seem to like anonymous functions. With the revised code, it will parse json into an object with a run property that is a
String, with value"function() { console.log('running...'); }". But when youeval(obj.run);, you will get a SyntaxError declaring an unexpected (. Presumably, this is the ( in function ().So, I can think of two ways of dealing with this:
function () {), and eval it. This means it will be called as soon as youevalit.What I think you want, is to be able to evaluate it to an anonymous function, that will be called when you want. So, you could write a wrapper function (you would need to follow option 1 for this as well):
This would allow you to call it. So:
Hope this helps!