JSON.stringify returns an empty set of square brackets when an associative array is passed.

RESOLVED INVALID

Status

()

Core
JavaScript Engine
RESOLVED INVALID
8 years ago
8 years ago

People

(Reporter: Matthew Morgan, Unassigned)

Tracking

Firefox Tracking Flags

(Not tracked)

Details

(Reporter)

Description

8 years ago
User-Agent:       Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2

If I pass an associative array (as created by assigning the output from the Array() constructor to a new variable, then adding elements) to the native JSON.stringify() function, it does not properly convert the array to json text.  It instead returns a string containing only "[]".  This does not happen when I pass a json string containing an associative array to JSON.parse, then run JSON.stringify on the array built from it.  That works as expected.

Reproducible: Always

Steps to Reproduce:
<html>
<head>
</head>

<body>

<pre>

<script language="javascript">

var myArray1 = Array();
myArray1["a0"] = "test1";
myArray1["b1"] = "test2";
myArray1["c2"] = "test3";

myArray2 = JSON.parse('{"a0":"test1","b1":"test2","c2":"test3"}');

document.writeln(JSON.stringify(myArray1));
document.writeln(JSON.stringify(myArray2));

</script>

</pre>

</body>
</html>
Actual Results:  
[]
{"a0":"test1","b1":"test2","c2":"test3"}


Expected Results:  
{"a0":"test1","b1":"test2","c2":"test3"}
{"a0":"test1","b1":"test2","c2":"test3"}
> var myArray1 = Array();
...
> document.writeln(JSON.stringify(myArray1));

Here you stringify an Array instance, not an "associative array" -- there is no such thing in JS. What happens in the elided (...) lines is immaterial.

> myArray2 = JSON.parse('{"a0":"test1","b1":"test2","c2":"test3"}');

Here you parse a JSON object literal, not a JSON array literal. There is no such thing as an "associative array" in JSON.

/be
Status: UNCONFIRMED → RESOLVED
Last Resolved: 8 years ago
Resolution: --- → INVALID
(Reporter)

Comment 2

8 years ago
Ah.  Thanks for the info.  I did do quite a bit of digging on the internet before posting this, and there was talk of associative arrays in JSON, but I guess this just turns out to be bad information.

Again, thanks for the quick response and a good lesson.
Matthew, note that if by "associative array" you basically mean "a set of keys and values", then a JS Object is more or less what you want (and will stringify as you seem to expect).
(Reporter)

Comment 4

8 years ago
Thank you, Boris.  Object are in fact working perfectly for me now that I know that's how I have to do it.  I was doing everything server side with associative arrays, so I wanted to do the same in my javascript to be symetrical.  Instead, I just switched both sides to using objects and I'm on my way!
You need to log in before you can comment on or make changes to this bug.