There is a previous question (here), however the answers there does not answer my question exactly - the accepted answer contained invalid JSON (mandating the use of eval()
), which is simply not possible to do even something like that as far as I am aware.
I'm planning to use code from my own server that is stored as object literal syntax in a string, however I'd like the ability to store functions in there as well.
Currently, I've thought of the following possibilities:
- Simply use
eval()
to parse the string - Place functions in string form (with something like
"\bfunction"
to be able to identify them), runningJSON.parse()
on it and then use a for-in loop to see whether any such functions need to be parsed (probably quite slow) - Use the DOM to run the code using a
<script>
tag and just run it there
This code will not contain anything that's supposed to be user-editable, however I'm not sure whether there would still be a safety issue or just a speed one. Would using eval()
be appropriate for my situation, and is there a more effective method of doing this than parsing for functions manually or using eval()
?
EDIT: would an alternative syntax to parse be better or would that just make things even more complicated?
EDIT2: I'm looking simply to do something like the following:
{ "test": function () {}
, "foo": 1
, "bar": 2 }
I'm not looking to just parse an entire function from a string, e.g.
eval('function(){}');