使用eval()

时间:2015-06-19 01:32:14

标签: javascript json reactjs

我正在将以下JSON变量转换为字符串。回到JSON时,我收到了错误(在ReactJS中,虽然它不重要)。

var questionGlobal = {
  "questionCons": [{
    "string": "In",
    "alignment": 2
  }, {
    "string": "New York State",
    "alignment": 1
  }, {
    "string": "the",
    "alignment": -1
  }, {
    "string": "shortest",
    "alignment": -1
  }, {
    "string": "period",
    "alignment": 0
  }, {
    "string": "of",
    "alignment": 2
  }, {
    "string": "daylight",
    "alignment": 0
  }, {
    "string": "occurs",
    "alignment": 2
  }, {
    "string": "during",
    "alignment": 1
  }, {
    "string": "which",
    "alignment": 0
  }, {
    "string": "month",
    "alignment": 0
  }],
  "options": [{
    "string": "January",
    "alignment": 1
  }, {
    "string": "December",
    "alignment": 2
  }, {
    "string": "June",
    "alignment": 1
  }, {
    "string": "July",
    "alignment": 1
  }]
};

这是命令:

window.console.log( eval(JSON.stringify(questionGlobal)));

我在控制台中获得的输出是:

  

未捕获的SyntaxError:意外的令牌

知道我做错了吗?

1 个答案:

答案 0 :(得分:10)

您可以使用JSON.parse

console.log(JSON.parse(JSON.stringify(questionGlobal)));

使用eval()时,需要传递有效的JS语句。你实际上可以在没有eval的情况下编写并且没有任何错误。

JSFiddle Demo