1

I would like to use stringify for encode my javascript array in json

params["margin_left"] = "fd";
params["text"] = "df";
params["margin_to_delete"] = "df";

console.info(params);

returns (Chrome console) :

[margin_left: "fd", text: "df", margin_to_delete: "df"]

but when I call :

console.info( JSON.stringify(params) );

I get

[]

Anyone knows why ?

Thanx

Paul
  • 1,290
  • 6
  • 24
  • 46
  • 4
    Make sure you are defining params as an object `var params = {};`, by the looks of it the bug may be that "params" is defined as an array (thus when stringified being empty since the attributes added via `params["margin_left"]` aren't looked at, only the actual array values) – Carl Feb 21 '14 at 13:39
  • 1
    That's an object. [And your code does work](http://jsfiddle.net/tR8jT/1/), assuming you declare `params` properly. – Andy Feb 21 '14 at 13:39
  • http://jsfiddle.net/ARZX5/ – damian Feb 21 '14 at 13:40
  • How did you declare your array? – ltalhouarne Feb 21 '14 at 13:41
  • answer here : http://stackoverflow.com/questions/7089118/convert-a-javascript-associative-array-into-json-object-using-stringify-and-vice – Carlo Moretti Feb 21 '14 at 13:42
  • var params = new Array(); – Paul Feb 21 '14 at 13:43

2 Answers2

1

Just to make my original comment an answer.

The issue is "params" is being defined as an array, ie.

var params = [];
params["margin_left"] = "fd";
params["text"] = "df";
params["margin_to_delete"] = "df";

Meaning that when stringify if called, it returns what it has - a blank array. (javascript doesn't support associative arrays, what the above code is actually doing is adding additional attributes to the array object, which do exist, although will be ignored for the purposes of iterating/stringifying)

By making it an object, everything should work as expected

var params = {};
params["margin_left"] = "fd";
params["text"] = "df";
params["margin_to_delete"] = "df";

Since now when stringify is called, javascript knows its the attributes you want.

Carl
  • 1,816
  • 13
  • 17
0

As Carl pointed, you must define params as object

var params = {};

Then you can use stringify to convert to JSON String, like this:

console.info( JSON.stringify(params) );