1

I want to serialize in json a non associative array and the output is quite disturbing

JSON.stringify([1]);
// Expected : "[1]"
Output : "\"[1]\""

It treats the array as a string, what am i missing ?

I'm using Chrome Version 29.0.1547.65

Guillaume Thomas
  • 2,220
  • 2
  • 24
  • 33

1 Answers1

3

The issue you are seeing is because of an Array.prototype.toJSON method that has been defined incorrectly with respect to the semantics of JSON.stringify. See below:

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

When an object has a toJSON method the result of that method will be stringified in its place. If the toJSON method is defined as a stringification then the object will be double stringified.

The only work-around I am aware of is to remove the method or to implement your own stringify() method with different semantics than the built-in.

If you can, simply remove the method from Array.prototype. If you are concerned this will break other functionality on the page then you need to remove it, stringify, then restore it.

function myStringify( o ) {
    var temp = Array.prototype.toJSON;
    delete Array.prototype.toJSON;
    var result = JSON.stringify(o);
    Array.prototype.toJSON = temp;

    return result;
}
Mike Edwards
  • 3,742
  • 17
  • 23