在 JSON 中表示 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21120999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Representing null in JSON
提问by pherris
What is the preferred method for returning null values in JSON? Is there a different preference for primitives?
在 JSON 中返回空值的首选方法是什么?对原语有不同的偏好吗?
For example, if my object on the server has an Integer called "myCount" with no value, the most correct JSON for that value would be:
例如,如果我在服务器上的对象有一个名为“myCount”的没有值的整数,则该值最正确的 JSON 将是:
{}
or
或者
{
"myCount": null
}
or
或者
{
"myCount": 0
}
Same question for Strings - if I have a null string "myString" on the server, is the best JSON:
字符串的相同问题 - 如果我在服务器上有一个空字符串“myString”,则是最好的 JSON:
{}
or
或者
{
"myString": null
}
or
或者
{
"myString": ""
}
or (lord help me)
或(上帝帮帮我)
{
"myString": "null"
}
I like the convention for collections to be represented in the JSON as an empty collection http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html
我喜欢在 JSON 中将集合表示为空集合的约定http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html
An empty Array would be represented:
将表示一个空数组:
{
"myArray": []
}
EDIT Summary
编辑摘要
The 'personal preference' argument seems realistic, but short sighted in that, as a community we will be consuming an ever greater number of disparate services/sources. Conventions for JSON structure would help normalize consumption and reuse of said services. As far as establishing a standard, I would suggest adopting most of the Hymanson conventions with a few exceptions:
“个人偏好”的论点似乎是现实的,但短视的是,作为一个社区,我们将消耗越来越多的不同服务/来源。JSON 结构的约定将有助于规范所述服务的使用和重用。至于建立标准,我建议采用大多数Hyman逊公约,但有一些例外:
- Objects are preferred over primitives.
- Empty collections are preferred over null.
- Objects with no value are represented as null.
- Primitives return their value.
- 对象优于基元。
- 空集合优于空集合。
- 没有值的对象表示为空。
- 原语返回它们的值。
If you are returning a JSON object with mostly null values, you may have a candidate for refactoring into multiple services.
如果您返回的 JSON 对象大部分为空值,则您可能有一个可以重构为多个服务的候选对象。
{
"value1": null,
"value2": null,
"text1": null,
"text2": "hello",
"intValue": 0, //use primitive only if you are absolutely sure the answer is 0
"myList": [],
"myEmptyList": null, //NOT BEST PRACTICE - return [] instead
"boolean1": null, //use primitive only if you are absolutely sure the answer is true/false
"littleboolean": false
}
The above JSON was generated from the following Java class.
上面的 JSON 是从以下 Java 类生成的。
package Hymanson;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.Hymanson.databind.ObjectMapper;
public class HymansonApp {
public static class Data {
public Integer value1;
public Integer value2;
public String text1;
public String text2 = "hello";
public int intValue;
public List<Object> myList = new ArrayList<Object>();
public List<Object> myEmptyList;
public Boolean boolean1;
public boolean littleboolean;
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new Data()));
}
}
Maven dependency:
Maven 依赖:
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-core</artifactId>
<version>2.3.0</version>
</dependency>
采纳答案by brandonscript
Let's evaluate the parsing of each:
让我们评估每个的解析:
http://jsfiddle.net/brandonscript/Y2dGv/
http://jsfiddle.net/brandonscript/Y2dGv/
var json1 = '{}';
var json2 = '{"myCount": null}';
var json3 = '{"myCount": 0}';
var json4 = '{"myString": ""}';
var json5 = '{"myString": "null"}';
var json6 = '{"myArray": []}';
console.log(JSON.parse(json1)); // {}
console.log(JSON.parse(json2)); // {myCount: null}
console.log(JSON.parse(json3)); // {myCount: 0}
console.log(JSON.parse(json4)); // {myString: ""}
console.log(JSON.parse(json5)); // {myString: "null"}
console.log(JSON.parse(json6)); // {myArray: []}
The tl;drhere:
The fragment in the json2variable is the way the JSON specindicates
nullshould be represented. But as always, it depends on what you're doing -- sometimes the "right" way to do it doesn't always work for your situation. Use your judgement and make an informed decision.
该TL;博士在这里:
json2变量中的片段是JSON 规范指示
null应表示的方式。但与往常一样,这取决于您在做什么——有时“正确”的方式并不总是适合您的情况。运用您的判断力并做出明智的决定。
JSON1 {}
JSON1 {}
This returns an empty object. There is no data there, and it's only going to tell you that whatever key you're looking for (be it myCountor something else) is of type undefined.
这将返回一个空对象。那里没有数据,它只会告诉您您正在寻找的任何密钥(无论是它myCount还是其他东西)都是 type undefined。
JSON2 {"myCount": null}
JSON2 {"myCount": null}
In this case, myCountis actually defined, albeit its value is null. This is notthe same as both "not undefinedand not null", and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail.
在这种情况下,myCount实际上是定义的,尽管它的值为null。这是不一样的两个“不undefined,不null”,如果你是一个条件或其他测试,这可能会成功,而JSON1会失败。
This is the definitive way to represent nullper the JSON spec.
JSON3 {"myCount": 0}
JSON3 {"myCount": 0}
In this case, myCount is 0. That's not the same as null, and it's not the same as false. If your conditional statement evaluates myCount > 0, then this might be worthwhile to have. Moreover, if you're running calculations based on the value here, 0 could be useful. If you're trying to test for nullhowever, this is actually not going to work at all.
在这种情况下,myCount 为 0。这与 不同null,也与 不同false。如果您的条件语句评估myCount > 0,那么这可能值得拥有。此外,如果您根据此处的值运行计算,则 0 可能很有用。null但是,如果您尝试进行测试,这实际上根本不起作用。
JSON4 {"myString": ""}
JSON4 {"myString": ""}
In this case, you're getting an empty string. Again, as with JSON2, it's defined, but it's empty. You could test for if (obj.myString == "")but you could not test for nullor undefined.
在这种情况下,您将获得一个空字符串。同样,与 JSON2 一样,它已定义,但它是空的。您可以测试 ,if (obj.myString == "")但无法测试null或undefined。
JSON5 {"myString": "null"}
JSON5 {"myString": "null"}
This is probably going to get you in trouble, because you're setting the stringvalue to null; in this case, obj.myString == "null"however it is not== null.
这可能会给您带来麻烦,因为您将字符串值设置为 null;在这种情况下,obj.myString == "null"但它不是== null。
JSON6 {"myArray": []}
JSON6 {"myArray": []}
This will tell you that your array myArrayexists, but it's empty. This is useful if you're trying to perform a count or evaluation on myArray. For instance, say you wanted to evaluate the number of photos a user posted - you could do myArray.lengthand it would return 0: defined, but no photos posted.
这会告诉你你的数组myArray存在,但它是空的。如果您尝试对 进行计数或评估,这将非常有用myArray。例如,假设您想评估用户发布的照片数量 - 您可以这样做myArray.length,它会返回0:已定义,但没有发布照片。
回答by Nicholas Carey
nullis not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.
null不为零。这不是一个值,本身:它是变量,指示丢失的或未知的数据的域之外的值。
There is only one way to represent nullin JSON. Per the specs (RFC 4627and json.org):
null在 JSON 中只有一种表示方式。根据规范(RFC 4627和json.org):
2.1. Values A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true
2.1. Values A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true


回答by dnozay
There is only one way to represent null; that is with null.
只有一种表示方式null;那是与null.
console.log(null === null); // true
console.log(null === true); // false
console.log(null === false); // false
console.log(null === 'null'); // false
console.log(null === "null"); // false
console.log(null === ""); // false
console.log(null === []); // false
console.log(null === 0); // false
That is to say; if any of the clients that consume your JSON representation use the ===operator; it could be a problem for them.
也就是说; 如果任何使用您的 JSON 表示的客户端使用该===运算符;这对他们来说可能是个问题。
no value
没有价值
If you want to convey that you have an object whose attribute myCounthas no value:
如果你想表达你有一个属性myCount没有值的对象:
{ "myCount": null }
no attribute / missing attribute
没有属性/缺少属性
What if you to convey that you have an object with no attributes:
如果你要表达你有一个没有属性的对象怎么办:
{}
Client code will try to access myCountand get undefined; it's not there.
客户端代码将尝试访问myCount并获取undefined;它不在那里。
empty collection
空集合
What if you to convey that you have an object with an attribute myCountthat is an empty list:
如果您要表示您有一个myCount具有空列表属性的对象,该怎么办:
{ "myCount": [] }
回答by marcoseu
I would use nullto show that there is no value for that particular key. For example, use nullto represent that "number of devices in your household connects to internet" is unknown.
我会null用来表明该特定键没有价值。例如,用于null表示“您家中连接到互联网的设备数量”是未知的。
On the other hand, use {}if that particular key is not applicable. For example, you should not show a count, even if null, to the question "number of cars that has active internet connection" is asked to someone who does not own any cars.
另一方面,{}如果该特定键不适用,则使用。例如,即使null向不拥有任何汽车的人询问“具有活动互联网连接的汽车数量”这一问题,您也不应该显示计数。
I would avoid defaulting any value unless that default makes sense. While you may decide to use nullto represent no value, certainly never use "null"to do so.
我会避免默认任何值,除非该默认值有意义。虽然您可能决定使用null来表示没有价值,但肯定永远"null"不要这样做。
回答by Alexei Levenkov
I would pick "default" for data type of variable (nullfor strings/objects, 0for numbers), but indeed check what code that will consume the object expects. Don't forget there there is sometimes distinction between null/default vs. "not present".
我会为变量的数据类型(null对于字符串/对象,0对于数字)选择“默认” ,但确实检查将消耗对象的代码。不要忘记null/default 与“不存在”之间有时存在区别。
Check out null object pattern- sometimes it is better to pass some special object instead of null(i.e. []array instead of nullfor arrays or ""for strings).
查看空对象模式- 有时最好传递一些特殊对象而不是null(即[]数组而不是null数组或""字符串)。
回答by Wayne
This is a personal and situational choice. The important thing to remember is that the empty string and the number zero are conceptually distinct from null.
这是个人和情境选择。要记住的重要一点是,空字符串和数字零在概念上与null.
In the case of a countyou probably always want some valid number (unless the countis unknown or undefined), but in the case of strings, who knows? The empty string could meansomething in your application. Or maybe it doesn't. That's up to you to decide.
在 a 的情况下,count您可能总是想要一些有效的数字(除非 acount未知或未定义),但在字符串的情况下,谁知道呢?空字符串可能意味着您的应用程序中的某些内容。或者也许不是。这由你来决定。
回答by iggie
According to the JSON spec, the outermost container does not have to be a dictionary (or 'object') as implied in most of the comments above. It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null. No braces, no brackets, no quotes. You could specify a dictionary containing a key with a null value ({"key1":null}), or a list with a null value ([null]), but these are not null values themselves - they are proper dictionaries and lists. Similarly, an empty dictionary ({}) or an empty list ([]) are perfectly fine, but aren't null either.
根据JSON 规范,最外层的容器不必是上面大多数评论中暗示的字典(或“对象”)。它也可以是一个列表或一个空值(即字符串、数字、布尔值或空值)。如果要在 JSON 中表示空值,则整个 JSON 字符串(不包括包含 JSON 字符串的引号)只是null. 没有大括号,没有括号,没有引号。您可以指定一个包含具有空值 ( {"key1":null})键的字典,或具有空值 ( ) 的列表[null],但这些本身不是空值 - 它们是适当的字典和列表。类似地,空字典 ( {}) 或空列表 ( []) 都很好,但也不为空。
In Python:
在 Python 中:
>>> print json.loads('{"key1":null}')
{u'key1': None}
>>> print json.loads('[null]')
[None]
>>> print json.loads('[]')
[]
>>> print json.loads('{}')
{}
>>> print json.loads('null')
None

