想要改进这个问题吗? 更新问题,以便 editing this post 提供事实和引用来回答它.
关闭 3 年前。
我正在创建一个以 JSON 形式返回结果的 API。当值为 null 时,是否应在结果中包含键是否有当前最佳实践?例如:
{
"title":"Foo Bar",
"author":"Joe Blow",
"isbn":null
}
或
{
"title":"Foo Bar",
"author":"Joe Blow"
}
由于第二个较小,我倾向于这种风格,但我不确定是否有首选风格。从客户的 Angular 来看,这两种风格似乎在功能上是等效的。各有优劣?
最佳答案
我喜欢总是明确地包含 null,因为它具有意义。 省略属性会导致歧义。
只要您与服务器的协议(protocol)达成一致,上述任何一项都可以工作,但如果您从服务器传递空值,我相信这会使您的 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 )
https://stackoverflow.com/questions/11003424/