100

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?

Paul
  • 139,544
  • 27
  • 275
  • 264
jjathman
  • 12,536
  • 8
  • 29
  • 33
  • 8
    It is impossible to answer this correctly. The correct answer depends on the requirements of the application. The OP has simply selected the answer that suits his requirements. If your application needs to be able to distinguish between knowing if the "isbn" is null vs if the "isbn" may not have been sent from the server for another reason, you need to include it. – Jay Nov 05 '13 at 21:21
  • @Jacob Although I didn't say it, my intention with this question was that the "full" JSON representing the response was being returned. When a client can assume that there seems to be no functional difference between the two approaches. If the API would selectively not return keys/values then yes it would make a big difference which approach was taken. – jjathman Jul 14 '15 at 21:58
  • 1
    the benefit of the first representation is that the object schema is preserved, the presence of the property is not ambiguous based on data. in the second format this information is lost. JSON spec as such does not mandate either format AFAIK – Surya Pratap Nov 23 '16 at 12:07
  • I think there's nothing opinionated about this question. JSON is a standard. There should be a specification for it, and probably a bunch of RFC's. // On top of that, even opinionated questions can be acceptable. There have been discussions about this before on meta.stackexchange where they ruled that opinionated questions are fine from a point of sharing "best practices". – bvdb Dec 30 '20 at 17:54

5 Answers5

87

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 )
rushkeldon
  • 1,343
  • 1
  • 10
  • 13
  • 3
    Exactly, more people need to understand the difference between "", null, and undefined. The answer to this question is dependent on the users requirements. – Jay Nov 05 '13 at 21:20
  • 15
    +1. The person on the other end (who wrote the code) will be better served by explicit values. They may not be writing JavaScript ;-) – Steve11235 Nov 21 '13 at 19:50
  • 3
    Note that checking against null doesn't work with ==, === is required (because undefined == null)! – Tommy Dec 30 '14 at 19:44
  • exactly the first part of accepted answer is so wrong... – Srneczek May 22 '15 at 07:37
  • I would write `"propertyName" in objectFromJSON` instead of `objectFromJSON.hasOwnProperty("propertyName")`. Also, if you insist on using `hasOwnProperty` then write `Object.prototype.hasOwnProperty.call(objectFromJSON, "propertyName")` for safety. – Aadit M Shah Sep 17 '19 at 16:11
35

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).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 7
    +1 for *There is usually no need to distinguish between null (no value) and undefined (no given value).* There is even a handy operator for it `!= null` (non-strict intended) – Esailija Jun 12 '12 at 19:30
  • The only case I can think of would be testing if a browser supports a certain event type. For instance, `if( typeof onbeforepaste == "undefined")` to see if `onBeforePaste` is supported. Even then it makes no real difference since you can assign events all you want (they just won't do anything if unsupported). – Niet the Dark Absol Jun 12 '12 at 19:31
  • In that case I would test `"onbeforepaste" in document`, to test existence of the property. – Esailija Jun 12 '12 at 19:32
  • There you go, another reason why there's no need to differentiate! – Niet the Dark Absol Jun 12 '12 at 19:33
  • 6
    In terms of saving transferred bytes, compression is much more important than things like indexed arrays. http://web-resource-optimization.blogspot.no/2011/06/json-compression-algorithms.html Make sure that is the first thing you do. In most cases adding things like indexed arrays on top of that is what I would call premature optimization. Unless you are sending LARGE amounts of data. That also requires additional parsing, adding more complexity to your app. Gzipping is seamlessly done by the browser. (assuming the client is a browser) – Martin Hansen Jun 12 '12 at 21:54
  • 3
    With HTTPS becoming norm of the day (at least for apps with large userbase), compression goes for a toss. See http://en.wikipedia.org/wiki/CRIME_%28security_exploit%29 – gvaish Mar 21 '14 at 17:54
  • 7
    I would actually -1 this for "There is usually no need to distinguish between null" if I had reputation. From 2 reasons: 1. reasons to distinguish exist and theyr not rare 2. best practise is to always have values "well defined" that means always prevent any ambiguities - 2 meanings of 1 value is always evil - it should be pretty clear.. – Srneczek May 22 '15 at 07:35
  • This answer is a bit misleading. Having null values makes a difference when the properties are nested. You'll want to check if each level have a null value or not. – png Jun 20 '18 at 00:10
  • Null and undefined have to be treated differently by a generic client. If the server explicitly returns null, a client cannot replace it with a default value without further context knowledge. Take for example Python's dictionary get method: `{}.get('foo','bar')` returns the default value 'bar'. `{'foo':null}.get('foo','bar')` returns null, because it has to return the content of the array. – relet Jan 02 '20 at 09:47
24

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • 5
    There is no "undefined" in JSON, so I think he asks only whether to include "empty" properties or not - `{"prop":undefined}` is different from `{}`. – Bergi Jun 12 '12 at 19:30
  • 1
    Agreed, I am trying to explain that on the receiving end, if he is looking for a specific property to be set to null, it won't be. It will be undefined, if left out. – Brad Jun 12 '12 at 19:32
12

You should definitely include it if there is any need to distinguish between null and undefined since those have two different meanings in Javascript. You can think of null as meaning the property is unknown or meaningless, and undefined as meaning the property doesn't exist.

On the other hand, if there is no need for anyone to make that distinction then go ahead and leave it out.

Paul
  • 139,544
  • 27
  • 275
  • 264
1

When JSON is used as API data carrier, there is no difference if there is a null or empty (undefined) value. Probably, the empty is better because we save some payload size.

The difference appears for JSON-config files when you would like to edit something by hands. It is better to have nulls there instead of undefined props. This way you will give hints about the config props existence.

  • 1
    Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Jun 18 '15 at 07:51