在 JSON 中空与空的约定是什么?

我知道,在大多数编程场景中,当有0个元素时,优先选择空集合为空集合。然而,大多数使用 JSON (比如 JavaScript)的语言将空列表/对象视为 true,空对象视为 false。例如,在 JavaScript 中,这既是 true,也是 object:

{
"items_in_stock": {"widgets":10, "gadgets": 5}
}

但这也是事实:

{
"items_in_stock": {}
}

这是错误的:

{
"items_in_stock": null
}

对于 JSON 是否有空对象/列表的约定? 对于数字、布尔值和字符串又如何?

182383 次浏览

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

Empty array for empty collections and null for everything else.

There is the question whether we want to differentiate between cases:

  1. "phone" : "" = the value is empty

  2. "phone" : null = the value for "phone" was not set yet

If we want differentiate I would use null for this. Otherwise we would need to add a new field like "isAssigned" or so. This is an old Database issue.