I’m creating an API that returns results as JSON. Is there a current best practice for whether we should include keys in the result when the value is null? For example:
{
"title":"Foo Bar",
"author":"Joe Blow",
"isbn":null
}
or
{
"title":"Foo Bar",
"author":"Joe Blow"
}
Since the second is smaller I am leaning towards this style, but I’m not sure if there is a preferred style or not. From a client perspective it seems like both styles would be functionally equivalent. Any pros or cons to each?
The second will save a small amount on bandwidth, but if that were a concern you would also use indexed arrays instead of filling the JSON with keys. Clearly,
["Foo Bar","Joe Blow"]is much shorter than what you have now.In terms of usability, I don’t think it makes any difference. In both cases,
if(json.isbn)will skip to theelse. There is usually no need to distinguish betweennull(no value) andundefined(no given value).