Hi all,
Thanks for taking the time to test the code snippets I posted, and
replying. Sorry I didn't provide more information in the original post
regarding the environment I ran the code in. Here it is now:
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.1pre) Gecko/
20090731 Shiretoko/3.5.1pre
Firebug 1.4.0b3
Prototype 1.6.0.3
jQuery 1.3.2
The code snippets were run in Firebug, and also in small test pages
where the output was simply dumped into a container on the screen.
In all of the above, the goal was to be able to successfully encode
(stringify) and then decode (parse) an array of object literals of the
form:
[
{
name: "bob",
id: 3
},
{
name: "john",
id: 4
}
]
So the expected output is a JavaScript object (exactly the same as the
input), and the output I was getting instead was a string of the form:
"[{"name": "bob", "id": 3}, {"name": "john", "id": 4}]"
Finally. I did test both with and without quotes key names, which
although helping the JSON to qualify as "valid" (e.g.
http://www.jsonlint.com/),
made no difference
in the above tests.
I have been able to track down the issue, and it turns out that it is
related to a conflict with Prototype (tested: 1.6.0.3 and 1.6.1rc3).
Here is a simple file that can verify the problem:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/
TR/html4/strict.dtd">
<html>
<head>
<title>Native JSON Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/
prototype.js" type="text/javascript"></script>
<script type="text/javascript">
var test = function () {
//console.log(JSON.parse(JSON.stringify([{"name": "bob", "id":
3}, {"name": "john", "id": 4}])));
var output = document.getElementById("output");
output.innerHTML = JSON.parse(JSON.stringify([{"name": "bob",
"id": 3}, {"name": "john", "id": 4}]));
};
</script>
</head>
<body onload="test();">
<div id="output"></div>
</body>
</html>
Run first as is and you should see:
[{"name": "bob", "id": 3}, {"name": "john", "id": 4}]
which means that the stringified JSON was not parsed correctly, and is
returning a string instead of an object.
Next, try commenting out the Prototype include and running again. You
should now see:
[object Object],[object Object]
Success! (you can verify that it is indeed the same object by running
the function in Firebug).
If someone else could verify this for me on a different setting, it
would be much appreciated.
Thanks all,
Keith