Javascript:如何使用eval返回或解析对象文字? [英] Javascript: How to return or parse an object literal with eval?
问题描述
我有一个小库,它可以接收字符串并从中构造对象。例如,’-key val’
创建 { key: val}
。但是,我也在尝试扩展输入字符串的语法以采用简单的对象文字,例如'-key {key:'val'}' yield
{ key:{ key: val}}
但是结果仅为 { key: val}
。
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"}
.
为什么eval只返回 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" }
推荐答案
{key: val}
是一个块,而 key:
是一个标签。
{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]
这篇关于Javascript:如何使用eval返回或解析对象文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!