Reputation: 4313
I'm curious what is the algorithm the express uses to serialize objects to JSON and if there's a way to modify it.
I notice that it only serializes objects' own properties, which makes it difficult to send out objects that inherit from other objects. It also omits any properties whose value is undefined
. I understand that functionally, omitting them is the same as including them and saves bandwidth, but including them makes the JSON more discoverable for people reading it trying to figure out how to use an API.
In any case, it's a question more about how express does things and less about what my code should do :=)
Upvotes: 0
Views: 4075
Reputation: 10038
It also omits any properties whose value is undefined.
There are no properties whose value is undefined. If you read a property that does not exist, undefined will be returned, not because its value equals undefined, but because there is no value to return because there is no such property.
The set of undefined properties is (infinity - defined values).
var o = {};
o.x // undefined
If express uses the below algorithm to find properties, it will never find x.
for (var key in o) {
if (o.hasOwnProperty(key)) {
console.log(o[key]);
}
}
Upvotes: -1
Reputation: 161597
It isn't express
that does the serialization, it uses the standard serialization method stringify. You can do a certain amount of modification to how things are serialized using the replacer
argument, but it is not possible to force it to show undefined
values.
Upvotes: 7