JSON.stringify doesn't work with normal Javascript array

JavascriptJson

Javascript Problem Overview


I must be missing something here, but the following code (Fiddle) returns an empty string:

var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);

What is the correct way of JSON'ing this array?

Javascript Solutions


Solution 1 - Javascript

JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.

The JSON array data type cannot have named keys on an array.

When you pass a JavaScript array to JSON.stringify the named properties will be ignored.

If you want named properties, use an Object, not an Array.

const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);

Solution 2 - Javascript

Nice explanation and example above. I found this (https://stackoverflow.com/questions/710586/json-stringify-bizarreness) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}

it works fine and the output of the test:

console.log(json);

Result:

"{"a":"test","b":["item","item2","item3"]}"

Solution 3 - Javascript

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

Solution 4 - Javascript

Alternatively you can use like this

var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);

Like this you JSON-ing a array.

Solution 5 - Javascript

Another approach is the JSON.stringify() replacer function param. You can pass a 2nd arg to JSON.stringify() that has special handling for empty arrays as shown below.

const arr = new Array();
arr.answer = 42;

// {"hello":"world","arr":{"answer":42}}
JSON.stringify({ hello: 'world', arr }, function replacer(key, value) {
  if (Array.isArray(value) && value.length === 0) {
    return { ...value }; // Converts empty array with string properties into a POJO
  }
  return value;
});

Solution 6 - Javascript

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSherlockView Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptAdrienView Answer on Stackoverflow
Solution 3 - JavascriptJVE999View Answer on Stackoverflow
Solution 4 - Javascriptuser4023394View Answer on Stackoverflow
Solution 5 - Javascriptvkarpov15View Answer on Stackoverflow
Solution 6 - Javascriptuser2217603View Answer on Stackoverflow