JSON 是否应包含空值 [英] Should JSON include null values

查看:44
本文介绍了JSON 是否应包含空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个以 JSON 形式返回结果的 API.当值为空时,是否应该在结果中包含键,是否有当前的最佳实践?例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆