JSON 是否应该包含空值

我正在创建一个以 JSON 形式返回结果的 API。当值为空时,我们是否应该在结果中包含键,目前有没有这方面的最佳实践?例如:

{
"title":"Foo Bar",
"author":"Joe Blow",
"isbn":null
}

或者

{
"title":"Foo Bar",
"author":"Joe Blow"
}

由于第二个是较小的,我倾向于这种风格,但我不知道是否有一个首选的风格或没有。从客户的角度来看,这两种风格在功能上似乎是等价的。每一个都有利有弊吗?

93661 次浏览

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.

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.

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

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 )

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.