Community Tip - Did you know you can set a signature that will be added to all your posts? Set it here! X
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 ?
Solved! Go to Solution.
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;
}
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;
}
Thank you so much, I didn't know the trick, it's very helpful