I have a little library that takes strings and constructs objects out of them. For example '-key val'
creates {"key": "val"}
. However I'm trying to extend the syntax of the input string to take simple object literals too, such as '-key "{key: 'val'}"'
which should yield {"key" : {"key" : "val"}}
however the result is only {"key" : "val"}
.
Why does eval only return "val" and not the entire object? And is there a safer alternative then my solution?
// my code before the fix
var arg = '{key: "val"}'
var result = eval(arg)
// result is "val"
Below is my fix, which is very unsafe!
const fmt = require('util').format
var arg = '{key: "val"}'
var result = eval(fmt('()=>(%s)', arg))()
// result is { key : "val" }
var arg = '{key: "val"}' var result = eval(arg)
when eval parse it, the '{' will be thought of as code block, and
key:
is a label so I think you should usevar arg = '{key:"val"}' var result = eval('('+arg+')') //result {key:"val"}
{key: "val"}
is a block, andkey:
is a label.If you want to parse it as an object initializer, use it in a place which expects an expression, e.g.