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

Community Tip - Help us improve the PTC Community by taking this short Community Survey! X

Create JSON scheme with value to null

Dorian
6-Contributor

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 ?

1 ACCEPTED SOLUTION

Accepted Solutions
abrigode
7-Bedrock
(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
7-Bedrock
(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
6-Contributor
(To:abrigode)

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

Top Tags