Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's JSON.stringify doesn't take key-indexed (associative) arrays?

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?

like image 761
RocketNuts Avatar asked Aug 21 '14 09:08

RocketNuts


People also ask

How do you stringify an array in JSON?

Stringify a JavaScript Array. Use the JavaScript function JSON.stringify () to convert it into a string. The result will be a string following the JSON notation. You will learn how to send JSON to the server in the next chapter.

Why can't I have named Keys on an array in JSON?

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.

How to stringify a JavaScript Object?

Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation. myJSON is now a string, and ready to be sent ...

What is an arrays in JSON?

Arrays as JSON Objects. Example. [ "Ford", "BMW", "Fiat" ] Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.


1 Answers

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.

like image 73
Linial Avatar answered Nov 02 '22 08:11

Linial