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?
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.
Stringify a JavaScript ArrayIt is also possible to stringify JavaScript arrays: Imagine we have this array in JavaScript: const arr = ["John", "Peter", "Sally", "Jane"]; Use the JavaScript function JSON.
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.
It`s ok to use it with some primitives like Numbers, Strings or Booleans. As you can see, you can just lose unsupported some data when copying your object in such a way. Moreover, JavaScript won`t even warn you about that, because calling JSON. stringify() with such data types does not throw any error.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With