使用 eval() 在 JavaScript 中将字符串转换为 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30928513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion of string to JSON object in JavaScript with eval()
提问by Daniel
I am converting the following JSON variable to string. When back to JSON, I'm getting an error (in ReactJS, although it shouldn't be important).
我正在将以下 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
}]
};
Here is the command:
这是命令:
window.console.log( eval(JSON.stringify(questionGlobal)));
The output that I get in console is:
我在控制台中得到的输出是:
Uncaught SyntaxError: Unexpected token
未捕获的语法错误:意外的令牌
Any idea where I am doing it wrong?
知道我在哪里做错了吗?
回答by Incognito
You could use JSON.parse
.
你可以使用JSON.parse
.
console.log(JSON.parse(JSON.stringify(questionGlobal)));
When using eval()
it is required that you pass a valid JS statement. One you could actually write without the eval
and without getting any errors.
使用eval()
时需要传递有效的 JS 语句。您实际上可以在没有eval
并且没有任何错误的情况下编写。