If JSON contains null values

I am creating an API that returns results as JSON. Is there a best practice for whether to 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 one is less, I am inclined to this style, but I'm not sure if there is a preferred style or not. From the client’s point of view, it seems that both styles will be functionally equivalent. Any pros or cons for everyone?

+82
json javascript null undefined
Jun 12 '12 at 19:23
source share
5 answers

The second will save a small portion of the bandwidth, but if that was a problem, you would also use indexed arrays instead of populating JSON with keys. It’s clear that ["Foo Bar","Joe Blow"] much shorter than you have now.

As for usability, I don't think that matters. In both cases, if(json.isbn) will go to else . Usually there is no need to distinguish between null (no value) and undefined (without a given value).

+30
Jun 12 '12 at 19:27
source share

I'm always a fan, including null, explicitly, as that makes sense. Although omitting a property leaves ambiguity.

As long as your protocol with the server is consistent, any of the above actions may work, but if you pass null from the server, I think your APIs are more flexible later.

It should also be mentioned that the javascript hasOwnProperty function gives you additional information.

 /* 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 ) 
+71
Aug 22 '13 at 22:24
source share

In JavaScript, null means something very different from undefined .

Your JSON output should reflect what your application uses and needs in the specific context of using JSON data.

+19
Jun 12 '12 at 19:25
source share

You should definitely enable it if you need to distinguish between null and undefined , since they have two different values ​​in Javascript. You can think of null as a value that is unknown or meaningless, and undefined because this property does not exist.

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

+10
Jun 12 '12 at 19:25
source share

I think it makes no difference when you use JSON as the data behind the user.

The difference appears in the JSON-config files when the user must manually edit something. When you use the first example, you give the user some hint of the configuration.

0
Jun 18 '15 at 7:51
source share



All Articles