3

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.

3
  • Why can't you just use [] as the initial value of the array, and then push new elements into it? Commented Sep 15, 2017 at 22:19
  • Post your code so we can see how you're initializing the object and explain how to fix it. Commented Sep 15, 2017 at 22:20
  • Why is the server printing the object twice? It sounds like the server is replacing an empty array with null for some reason. Commented Sep 15, 2017 at 22:40

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

To initialize an empty array in javascript simply write it like

var arr = [];

Example for JSON

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.