Javascript: How to return or parse an object literal with eval?

浪尽此生 提交于 2019-12-11 04:46:39

问题


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 use
var 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!