javascript 为什么 JSON.parse 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5201541/
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
Why doesn't JSON.parse work?
提问by Shawn
Why doesn't JSON.parse behave as expected? In this example, the alert doesn't fire:
为什么 JSON.parse 没有按预期运行?在此示例中,警报不会触发:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing JSON.parse</title>
<script type="text/javascript" src="js/json2.js">
// json2.js can be found here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
</script>
<script type="text/javascript">
function testJSONParse()
{
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));
}
window.onload = testJSONParse;
</script>
</head>
<body>
</body>
</html>
In firefox, the Error Console says "JSON.parse". Not very descriptive..
在 Firefox 中,错误控制台显示“JSON.parse”。不太好描述。。
This is a simplification of a problem I have which uses AJAX to fetch data from a database and acquires the result as a JSON string (a string representing a JSON object) of the same form as textin the example above.
这是我遇到的问题的简化,它使用 AJAX 从数据库中获取数据并将结果作为与text上面示例中相同形式的 JSON 字符串(表示 JSON 对象的字符串)获取。
回答by Rocket Hazmat
Your JSON is not formatted correctly:
您的 JSON 格式不正确:
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
^-- This should be a ':'
It should be:
它应该是:
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
回答by Praveen Prasad
error in typing
打字错误
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
var text = '[{"a":"w","b" :"x"},{"a":"y","b":"z"}]';
//below is correct one
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));

