列表/数组是有效的 JSON 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19623339/
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
Is a list/array valid JSON?
提问by loneboat
I wish to write a webservice which serves lists of JSON objects. Is it valid JSON to return the following:
我希望编写一个提供 JSON 对象列表的网络服务。返回以下内容是否有效 JSON:
[
{"keyA1":"valA", "keyB1":"valB"}
,{"keyA2":"valA", "keyB2":"valB"}
,{"keyA3":"valA", "keyB3":"valB"}
]
Or is the "right" way to do it to put it in a single object to return:
或者是将它放在单个对象中以返回的“正确”方法:
{"elements":[
{"keyA1":"valA", "keyB1":"valB"}
,{"keyA2":"valA", "keyB2":"valB"}
,{"keyA3":"valA", "keyB3":"valB"}
]}
回答by Chris Hayes
Both forms are valid. However, for an API, I would recommend the second form. The reason is that it gives you a path for expansion of your API.
两种形式都有效。但是,对于 API,我会推荐第二种形式。原因是它为您提供了扩展 API 的途径。
For example, if you have an API getUsersInGroupwhich returns an array of user objects, and later you decide you want to include, say, some aggregate statistics about the users being returned, there's no easy way to do that without breaking existing clients (or including lots of redundant data in each user object). If you use an object, you simply add another field to the object which is silently ignored by clients on a previous version of the API.
例如,如果您有一个getUsersInGroup返回用户对象数组的 API ,然后您决定要包括,例如,有关返回用户的一些汇总统计信息,则没有简单的方法可以在不破坏现有客户端(或包括每个用户对象中有大量冗余数据)。如果您使用一个对象,您只需向该对象添加另一个字段,该对象在以前版本的 API 上会被客户端静默忽略。
In short, try to avoid top-level primitives wherever possible in your API, and you'll find it easier to expand in the future.
简而言之,尽量避免在您的 API 中使用顶级原语,您会发现将来扩展起来会更容易。
回答by JDong
Both are valid JSON, but the second way is correct; passing JSON around as an array can lead to security vulnerabilities. See a related poston JSON security to learn more about this. In some frameworks, such as flask, there are even measures that prevent you from passing around JSON as an array.
两者都是有效的 JSON,但第二种方式是正确的;将 JSON 作为数组传递可能会导致安全漏洞。请参阅有关JSON 安全性的相关帖子以了解有关此内容的更多信息。在某些框架中,例如 Flask,甚至有一些措施可以防止您将 JSON 作为数组传递。
回答by Sergei Beregov
You can validate JSON using http://jsonlint.com/
您可以使用http://jsonlint.com/验证 JSON
Both are valid JSON results but I'd use the second one. It's more logical and descriptive.
两者都是有效的 JSON 结果,但我会使用第二个。它更具逻辑性和描述性。

