JSON应该包含空值 [英] Should JSON include null values
问题描述
我正在创建一个以JSON格式返回结果的API。当值为null时,是否应该在结果中包含键,是否存在当前的最佳实践?例如:
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
}
或
{
"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?
推荐答案
第二个会节省一小部分带宽,但如果这是一个问题你会也使用索引数组,而不是用键填充JSON。显然, [Foo Bar,Joe Blow]
比你现在的要短得多。
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.
在可用性方面,我认为它没有任何区别。在这两种情况下, if(json.isbn)
将跳转到 else
。通常无需区分 null
(无值)和 undefined
(无给定值)。
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).
这篇关于JSON应该包含空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!