Should JSON include null values [closed]
I am a fan of always including null explicitly as that carries meaning.While omitting a property leaves ambiguity.
As long as your protocol with the server is agreed upon any of the above can work, but if you pass nulls from the server I believe that makes your APIs more flexible later.
Should also mention that javascript's hasOwnProperty function gives you further insight.
/* if true object DOES contain the property with *some* value */if( objectFromJSON.hasOwnProperty( "propertyName" ) )/* if true object DOES contain the property and it has been set to null */if( jsonObject.propertyName === null )/* if true object either DOES NOT contain the property OR object DOES contain the property and it has been set to undefined */if( jsonObject.propertyName === undefined )
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 the else
. There is usually no need to distinguish between null
(no value) and undefined
(no given value).
In JavaScript, null
means something very different than undefined
.
Your JSON output should reflect what is used and needed by your application in the specific context of using the JSON data.