Skip to content Skip to sidebar Skip to footer

Javascript: How To Return Or Parse An Object Literal With Eval?

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 s

Solution 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]

Solution 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"}

Post a Comment for "Javascript: How To Return Or Parse An Object Literal With Eval?"