jzeef
jzeef

Reputation: 729

Assign Empty Array to JSON object insted of null

So I'm currently adapting a python-based GUI to a javascript based web GUI. The program sends large JSON messages to some server for processing. The server recieves messages in which some values are set like so:

"someVar": []

However, I don't know how to send this in the same way from my own GUI in javascript. My solutions result in this:

"someVar": null

The server doesn't like this, but I cannot find a way to assign an empty array without it defaulting to null.

The object starts out like so:

{
  var1: null
  var2: "someString"
  var3: 1.3
  ...
}

when the server gets this, it normally prints out

{
  var1: []
  var2: "someString"
  var3: 1.3
  ...
}

so lets say this object is stored in a variable called curConfig

I want to do something like this:

curConfig['var1'] = []

But that still leaves me with a null value instead of [] when it gets sent to the server.

Upvotes: 3

Views: 13118

Answers (3)

Ori Drori
Ori Drori

Reputation: 191986

If you have a large number of null values that you want to change to empty array when using JSON#stringify, you can use a replace function (2nd param):

JSON.stringify(value[, replacer[, space]])

The function receives the key and the value, and you can decide, which value you want to return.

var data = {
  var1: null,
  var2: "someString",
  var3: 1.3
};

var reslut = JSON.stringify(data, function(key, value) {
  if (value === null) {
    return [];
  }
  return value;
});

console.log(reslut);

Upvotes: 3

Barmar
Barmar

Reputation: 781129

Initialize the object like this:

{
  var1: [],
  var2: "someString",
  var3: 1.3,
  ...
}

Also,

curConfig.var1 = [];

should work, I don't know why it isn't working for you.

Upvotes: 1

anteAdamovic
anteAdamovic

Reputation: 1468

To initialize an empty array in javascript simply write it like

var arr = [];

Example for JSON

var obj = {
  arr: []
};
JSON.stringify(obj); // "{ "arr": [] }"

Upvotes: 1

Related Questions