5

In JavaScript, you can have objects, like this:

var a = { foo: 12, bar: 34 };

Or arrays with key (named) indexes, like this:

var b = [];
b['foo'] = 56;
b['bar'] = 78;

They're somewhat similar, but obviously not the same.

Now the strange thing is, JSON.stringify doesn't seem to take the array. No errors or anything, JSON.stringify(b) just results in [].

See this jsfiddle example. Am I doing something wrong, or do I just misunderstand how arrays work?

RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • 1
    possible duplicate of [JSON.stringify doesn't work with normal Javascript array](http://stackoverflow.com/questions/16196338/json-stringify-doesnt-work-with-normal-javascript-array) – Yuliam Chandra Aug 21 '14 at 09:07

3 Answers3

6

Javascript doesn't support Associative arrays (Like PHP).

var b = []; Declaring explicitly an array, when you are trying to create an Object.

Arrays in Javascript can only contain the Index approach of Arrays, while Objects are more of Associative arrays.

If you change var b = []; to var b = {}; it will solve the problem.

var b = {} Declaring explicitly an Object.

adiga
  • 34,372
  • 9
  • 61
  • 83
Linial
  • 1,154
  • 9
  • 22
  • What do you mean, doesn't support associative arrays? The above works (except for the json stringify), afterwards I can use b['foo'] and b['bar'] and it gives the expected result. – RocketNuts Aug 21 '14 at 09:26
  • I have created a Fiddle for you to understand. http://jsfiddle.net/shaharlini/xLw2p54e/ JSON -> Javascript Object Notation. Please look at here to read some more from Mozilla MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify – Linial Aug 21 '14 at 10:20
5

Javascript arrays are objects. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object for details.

Note: if you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.

JSON supports only a subset of Javascript. See http://www.json.org/ for details.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

A Javascript array that has properties created in the underlying object does not fit into either of these structures because it has both a collection of name/value pairs and an ordered list of values, so there is no simple way to represent such an object directly in JSON.

The JSON.stringify method is defined in the ECMAScript specification. For example, see http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3.

While there are many details, the bit that is relevant here is how object values are stringified:

If Type(value) is Object, and IsCallable(value) is false

  • If the [[Class]] internal property of value is "Array" then Return the result of calling the abstract operation JA with argument value.
  • Else, return the result of calling the abstract operation JO with argument value.

Given your array, despite the addition of parameters to the underlying object, the result is of stringifying the ordered set of array elements, not the underlying object.

There is nothing wrong about adding parameters to an array object, but they are not part of the array and functions or methods that handle arrays might ignore them or deal with them arbitrarily. You have seen that JSON.stringify ignores the additional parameters. Other functions might do otherwise - you will have to find out in each case.

While it is not wrong, it will probably be easier to understand if you do not add properties to array objects. If you want to add properties, start with a non-array object.

Rather than:

var b = [];
b['foo'] = 56;
b['bar'] = 78;

You might use:

var b = {};
b['foo'] = 56;
b['bar'] = 78;
Ian
  • 2,078
  • 2
  • 19
  • 19
1

enter image description here

This snap is from IE explorer. See the array is still blank.

Actually the way of inserting the elements to the array is :

1. Use push() 2. insert the elements in the array during declaration

If you want to stringify the array you have to have the data inside the array.

So, now you want to stringify the key value pairs so you have to pass the object as the argument of JSON.stringify() as follows:

var test = {};           // Object
test['a'] = 'test';
test['b'] = [];          // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);

Solution to your problem now:

enter image description here

Note: Console of Google Chrome is giving different result, which is a bug in Google Chrome.

Vishal
  • 537
  • 3
  • 13
  • Isn't that a bug in IE? (it usually is...) To put simly, does this say Hello or not: var b=[]; b['x']='Hello'; alert(b['x']); – RocketNuts Aug 21 '14 at 10:39
  • but this is not the way of inserting values to an array(check the api documentation of javascript). Moreover, everything is object in javaScript so b['x'] notation is valid for inserting values in array as javascript thinks that a key value pair is created corresponding to the object.. but as soon as it determines that b is an array it does not insert the value in array.. so the array will always be blank in such a case.. therefore JSON.stringify() returns empty array. JSON.stringify() can't be wrong Sir. – Vishal Aug 21 '14 at 10:45
  • always remember arrays in any language accepts the value corresponding to the INDEXES. This is programming grammar – Vishal Aug 21 '14 at 10:46