Search code examples
javascriptstringify

stringify doesn't works with my javascript array


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


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.