Why the open quote and bracket for eval('(' + jsonString+ ')') when parsing json string

后端 未结 3 2009
梦谈多话
梦谈多话 2020-11-27 21:02

Can you please tell me the reason for this specific syntax structure

 eval(\'(\' + jsonString+ \')\')

When parsing json text. Crockford sa

3条回答
  •  隐瞒了意图╮
    2020-11-27 21:46

    An object literal needs to be wrapped in parentheses to properly be evaluated in eval context and other contexts:

    eval('{}') is undefined, for example. whereas eval('(' + '{}' + ')' ) evaluates to Object.

    If you tried this in the console, for example: {"foo":"bar"} it would throw an invalid label at you. Wrap it in parentheses and it becomes a valid expression.

提交回复
热议问题