JSON.stringify doesn't work with normal Javascript array

json.stringify array
json.stringify replacer
json.stringify pretty
json stringify online
json stringify array of objects
json.stringify reverse
json stringify java
json stringify python

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 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);

JSON.stringify doesn't work with normal Javascript array, string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.

Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) 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"]}"

Reverse of JSON.stringify?, you should use your loop directly on the values array. From the document of JSON.stringify(), For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized. and Error object doesn't have its enumerable properties, that's why it prints an empty object. answered Jun 7 '18 at 9:50

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);
    };
})();

Get JSON stringify value, What is the difference between JSON parse and JSON Stringify? The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. The source for this interactive example is stored in a GitHub repository.

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.

Difference between JSON.stringify and JSON.parse, Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to  I have used the following method: JSON.stringify(json,null,2); This produces tabbed output in all browsers except IE: in IE, it displays a single line. Is null the problem and if so what are the

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});

JSON.stringify(), So where does the drama with toString() come in? Well, let's start by pretending that we need to turn an object into a string. Making objects into  To begin with, JSON.Stringify() is a function which is inbuilt in JSON. With the help of it, you can create a JSON string from a JavaScript Array or Object. With the help of it, you can create a JSON string from a JavaScript Array or Object.

JavaScript JSON stringify() Method, There are several edge cases where JSON.stringify() doesn't throw an error, but you might expect it does. For example, JSON.stringify()  JSON.stringify() doesn't know how to serialize a BigInt #30. cliffhall opened this issue Aug 14, 2019 · 2 comments Comments. Copy link Quote reply

Everything You Need To Know About JSON.stringify and JSON.parse, parse() takes a JSON string and then transforms it into a JavaScript object. Let's take a look at a code example: JSON.stringify() can take  stringify(obj, serializer, indent, decycler) The first three arguments are the same as to JSON.stringify. The last is an argument that's only used when the object has been seen already. The default decycler function returns the string '[Circular]'.

The 80/20 Guide to JSON.stringify in JavaScript, JSON.stringify() takes a JavaScript object and transforms it into a JSON string. Here's an example: const myObj = { name  I need to use: JSON.stringify() which should be supported by Chrome, Safari, and Firefox. I think IE8 also has support for the JSON object. I think IE7 and 6 do not, so I'm doing this: <!--[i

Comments
  • That's not an array, you are just setting two properties
  • possible duplicate of JavaScript associative array to JSON
  • Start out with var test = {}; instead
  • I have been hitting my head against a wall because I was doing exactly this. Thank you :)
  • I had some issues with a site that overwrite Date, so when I use the Date.toJSON fails I so I added: Date.prototype.toJSON = Date.prototype.toISOString;
  • This is just wrong. JSON.stringify([15,12]) will work. It will give "[15,12]"