Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify doesn't work with normal Javascript array

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?

like image 430
Sherlock Avatar asked Apr 24 '13 15:04

Sherlock


People also ask

Why JSON Stringify does not work on 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.

Can we use JSON Stringify for 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.

What happens when you JSON Stringify an array?

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.

Is it bad to use JSON Stringify?

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.


1 Answers

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);
like image 193
Quentin Avatar answered Sep 29 '22 03:09

Quentin