javascript - JSON 是否应该包含空值

我正在创建一个以 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/

相关文章:

c# - 解析值时遇到意外字符

javascript - 将 JSON 发送到服务器并返回 JSON,无需 JQuery

json - AngularJS:工厂 $http.get JSON 文件

python - 如何在 Python 中美化 JSON?

json - json.js 和 json2.js 的区别

python - 如何在单元测试中使用 JSON 发送请求

javascript - 未捕获的类型错误 : Cannot use 'in' operator t

json - 在 VS Code 中,禁用错误 "Comments are not permitte

javascript - JSON Stringify 因 UTC 而更改日期时间

javascript - 请求的资源错误中不存在 'Access-Control-Allow-Ori