问题
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" }
回答1:
{key: "val"}
is a block, and key:
is a label.
If you want to parse it as an object initializer, use it in a place which expects an expression, e.g.
({key: "val"})
0,{key: "val"}
[{key: "val"}][0]
回答2:
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"}
来源:https://stackoverflow.com/questions/38517452/javascript-how-to-return-or-parse-an-object-literal-with-eval