为什么JSON.parse没有工作?

时间:2021-08-07 20:17:03

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 text in the example above.

这是我所遇到的问题的简化,它使用AJAX从数据库中获取数据,并将结果作为JSON字符串(表示JSON对象的字符串)获取,其形式与上例中的文本相同。

2 个解决方案

#1


10  

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"}]';

#2


2  

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));

#1


10  

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"}]';

#2


2  

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));