Skip to main content
10-Marble
November 20, 2019
Solved

Create JSON scheme with value to null

  • November 20, 2019
  • 1 reply
  • 1364 views

Hello,

 

I want to create a service with JSON output, I want the output to always have the same structure.
For example my structure is composed of 3 fields (field1, field2 and field3), sometimes one or several fields are null, but I want to see them in my output, regardless.

In my code I have :

 

result = {

field1 : "some value",

field2 : null,

field3 : "other value"

}

 

but my service gives me only :

 {

field1 : "some value",

field3 : "other value"

}

 

How can I have field2 please ?

Best answer by abrigode

Hi Dorian, I was able to get the null output by using the optional replacer parameter (as a function) of JSON.stringify(). I did the following with your sample data.

 

var test = {

     "field1" : "some value",

     "field2" : null,

     "field3" : "other value"

};

 

var result = JSON.stringify(test, replacer);

 

function replacer(key, value) {

     if (value == null) {

          return null;

     }

     return value;

}

1 reply

abrigode12-AmethystAnswer
12-Amethyst
November 20, 2019

Hi Dorian, I was able to get the null output by using the optional replacer parameter (as a function) of JSON.stringify(). I did the following with your sample data.

 

var test = {

     "field1" : "some value",

     "field2" : null,

     "field3" : "other value"

};

 

var result = JSON.stringify(test, replacer);

 

function replacer(key, value) {

     if (value == null) {

          return null;

     }

     return value;

}

Dorian10-MarbleAuthor
10-Marble
November 21, 2019

Thank you so much, I didn't know the trick, it's very helpful