我正在创建一个以JSON格式返回结果的API。当值为空时,我们是否应该在结果中包含键,是否有当前的最佳实践?例如:
{
"title":"Foo Bar",
"author":"Joe Blow",
"isbn":null
}
或
{
"title":"Foo Bar",
"author":"Joe Blow"
}
由于第二个较小,我倾向于这种风格,但我不确定是否有首选的风格。从客户的角度来看,这两种风格似乎在功能上是相同的。每一种都有什么利弊?
发布于 2012-06-13 03:27:39
第二种方法将节省少量的带宽,但如果需要考虑这一点,您还可以使用索引数组,而不是使用键填充JSON。显然,["Foo Bar","Joe Blow"]
比您现在拥有的要短得多。
在可用性方面,我不认为这有什么不同。在这两种情况下,if(json.isbn)
都会跳到else
。通常不需要区分null
(无值)和undefined
(无给定值)。
发布于 2013-08-23 06:24:41
我喜欢总是显式地包含null,因为这意味着有意义。而省略一个属性则会留下歧义。
只要您与服务器的协议达成一致,上面的任何一个都可以工作,但如果您从服务器传递空值,我相信这将使您的API稍后更加灵活。
还应该提到的是,javascript的hasOwnProperty函数给了你更多的洞察力。
/* 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 )
发布于 2012-06-13 03:25:23
在JavaScript中,null
的含义与undefined
非常不同。
JSON输出应该反映应用程序在使用JSON数据的特定上下文中使用和需要的内容。
https://stackoverflow.com/questions/11003424
复制相似问题