0

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

Iulian
  • 25
  • 5

3 Answers3

1

There are no associative arrays in javascript. They are called objects:

const smallObject = {
   ok: "not ok",
   not_ok: "ok"
};

const finalArray = [smallObject];

console.log(JSON.stringify(finalArray));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

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));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Objects in javacript are defined like this var obj = {}

var small_array = {},
final_array = {};

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

final_array = (small_array);

console.log(JSON.stringify(final_array));
VM1623:9 {"ok":"ok","not_ok":"not_ok"}