Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top