cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - If community subscription notifications are filling up your inbox you can set up a daily digest and get all your notifications in a single email. X

Create JSON scheme with value to null

Dorian
10-Marble

Create JSON scheme with value to null

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 ?

ACCEPTED SOLUTION

Accepted Solutions
abrigode
12-Amethyst
(To:Dorian)

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;

}

View solution in original post

2 REPLIES 2
abrigode
12-Amethyst
(To:Dorian)

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;

}

Dorian
10-Marble
(To:abrigode)

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

Announcements


Top Tags