JSON中对于空对空的约定是什么? [英] what is the convention in JSON for empty vs. null?

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

问题描述

我知道在大多数编程场景中,当有0个元素时,首选的是空集合为null集合。但是,大多数使用JSON的语言(如JavaScript)会将空列表/对象视为true,将null视为false。例如,这将是true和JavaScript中的对象:

I know that in most programming scenarios, the preference is for empty collections to null collections when there are 0 elements. However, most languages that consume JSON (like JavaScript) will treat empty lists/objects as true and null ones as false. For example this would be both true and an object in JavaScript:

{
    "items_in_stock": {"widgets":10, "gadgets": 5}
}

但这也是如此:

{
    "items_in_stock": {}
}

这是假的:

{
    "items_in_stock": null
}

是否有关于空对象/列表的约定对于JSON?那么数字,布尔值和字符串呢?

Is there a convention on empty objects/lists for JSON? And what about for numbers, booleans, and strings?

推荐答案

如果期望的返回,返回一个空数组是很好的编程习惯type是一个数组。这可以确保json的接收器可以立即将值视为一个数组,并且首先不必检查它是否为空。它与空对象({})的方式相同。字符串,布尔值和整数没有空形式,因此可以使用空值。

It is good programming practice to return an empty array if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately and does not first has to check if it is null. It's the same way with empty objects ({}). Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

不要相信我的话。在Joshua Blochs出色的书Effective Java中,他描述了一些非常好的通用编程实践(通常也适用于其他编程语言)。返回空集合而不是空值是其中之一。这是他书中那一部分的链接: http ://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

Don't take my word for it. In Joshua Blochs excellent book "Effective Java" he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them. Here's a link to that part of his book: http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

这篇关于JSON中对于空对空的约定是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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