While there is a similar question (here), the answers provided do not exactly address my query. The accepted answer included invalid JSON (forcing the use of eval()
), which seems to be an impossible solution as far as I know.
I intend to utilize code from my own server, stored in string format using object literal syntax, but I also wish to incorporate functions within it.
My current train of thought involves these possibilities:
- Directly applying
eval()
to parse the string - Enclosing functions in string format (possibly with something like
"\bfunction"
for identification), then utilizingJSON.parse()
followed by a for-in loop to check if any functions need parsing (which might be slow) - Utilizing the DOM to execute the code through a
<script>
tag and running it there
The code will not contain any user-editable content, but I am unsure if there could be a safety concern or simply a performance issue. Is the use of eval()
suitable in my scenario, and are there more efficient methods other than manually searching for functions or resorting to eval()
?
EDIT: Would opting for an alternative syntax for parsing be a better approach, or would it just add further complexity?
EDIT2: My goal is to achieve something along the lines of the following:
{ "test": function () {}
, "foo": 1
, "bar": 2 }
I am not aiming to solely parse an entire function from a string, for example:
eval('function(){}');