Should JSON include null values

jjathman picture jjathman · Jun 12, 2012 · Viewed 89k times · Source

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?

Answer

rushkeldon picture rushkeldon · Aug 23, 2013

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 )