Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't JSON.parse work?

Why doesn't JSON.parse behave as expected? In this example, the alert doesn't fire:

<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..

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.

like image 909
Shawn Avatar asked Dec 16 '22 16:12

Shawn


2 Answers

Your JSON is not formatted correctly:

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"}]';
like image 113
Rocket Hazmat Avatar answered Dec 19 '22 05:12

Rocket Hazmat


error in typing

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));
like image 42
Praveen Prasad Avatar answered Dec 19 '22 06:12

Praveen Prasad