Search code examples
javascriptjquerystringify

JSON.stringify multidimensional


I am trying to send a javascript object to PHP using JSON.stringify and I cannot find a solution. Here`s an example of what I have:

var small_array = [],
    final_array = [];

small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";

final_array.push(small_array);

console.log(JSON.stringify(final_array));

The output is "[[]]"

Any guidance on this one? Thanks


Solution

  • You're adding non-array-entry properties to the array. That's fine in JavaScript, but JSON doesn't have the notion of non-array-entry properties in an array (JSON arrays are just ordered sequences, whereas in JavaScript arrays are fully-fledged objects that provide special treatment to certain kinds of properties — more in my [ancient] blog post A Myth of Arrays).

    For those property names (keys), you'd want a plain object, not an array:

    var obj         = {}, // Note {}, not []
        final_array = [];
    
    obj["ok"] = "ok";
    obj["not_ok"] = "not_ok";
    
    final_array.push(obj);
    
    console.log(JSON.stringify(final_array));