json 和空数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8104573/
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
json and empty array
提问by elio.d
I have the following json :
我有以下 json :
{
"users":
[{
"user":
{
"user_id" :"a11uhk22hsd3jbskj",
"username" :"tom",
"location" : null
}
}]
}
I get this json in response to a request to an api. Looking at the doc for this api, location is supposed to be an array (containing geodata, latitude, longitude address etc).
Now the question is : there's an error in the json? I mean, location doesn't seems,to me, to be an array, or is possible to represent a null array in that way? and if yes what is the difference between :
我收到此 json 以响应对 api 的请求。查看此 api 的文档,位置应该是一个数组(包含地理数据、纬度、经度地址等)。
现在的问题是:json 中有错误?我的意思是,位置对我来说似乎不是一个数组,或者可以用这种方式表示一个空数组?如果是,有什么区别:
"location" : null
"location" : []
Thanks in advance
提前致谢
采纳答案by Hot Licks
nullis a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULLvalue) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.
null是JSON 中的合法值(和保留字),但某些环境没有“NULL”对象(与NULL值相反),因此无法准确表示 JSON null。所以他们有时会将它表示为一个空数组。
Whether nullis a legal value in that particular element of that particular API is entirely up to the API designer.
无论null是在那个特定的API的特定元素的合法值完全取决于是对API设计师。
回答by Matt Varblow
"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
看起来这个 API 在没有定义位置时返回 null - 而不是返回一个空数组,真的不是太不寻常 - 但他们应该告诉你他们是否要这样做。
回答by Adam Zalcman
The first version is a null object while the second is an Array object with zero elements.
第一个版本是一个空对象,而第二个版本是一个零元素的数组对象。
Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.
空在这里可能意味着例如没有位置可用于该用户、没有请求位置或应用了一些限制。不参考 API 很难说。

