javascript JSON 设计最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20513041/
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 design best practices
提问by hendry
I have designed a JSON representation of a mailbox so that I can look up mails easily, for example mailjson[UID].Body
.
我设计了一个邮箱的JSON表示,这样我可以看看邮件很容易,例如mailjson[UID].Body
。
However after looking at Angularjs and Ember, templating MVC JS engines, it seems that the JSON should be of the format:
然而,在查看了 Angularjs 和 Ember,模板 MVC JS 引擎之后,JSON 似乎应该是以下格式:
[{
"id": 1,
"body": "Blah blah blah..."
},
{
"id": 2,
"body": "More blah foo blah"
},
{
"id": 3,
"body": "Hopefully you understand this example"
}]
And then there is some findAll(id) function to grab the item based on the id one wants, that iterates through the JSON. So now I'm wondering does my JSON design have merit? Am I doing it wrong? Why don't people use the dict lookup design I'm using with my JSON?
然后有一些 findAll(id) 函数根据一个人想要的 id 来获取项目,它遍历 JSON。所以现在我想知道我的 JSON 设计有没有价值?我做错了吗?为什么人们不使用我在 JSON 中使用的 dict 查找设计?
Any other tips to make sure I have a good data structure design, I would be grateful.
任何其他确保我有一个好的数据结构设计的技巧,我将不胜感激。
回答by alpav
Best practice for storage of big table in JSON is to use array.
在 JSON 中存储大表的最佳实践是使用数组。
The reason is that when parsing JSON array into memory array there is no speed penalty of building map. If you need to build in-memory index by several fields for quick access, you can do it during or after loading. But if you store JSON like you did, you don't have a choice to load quickly without building map because JSON parser will always have to build that huge map of ids based on your structure.
原因是在将 JSON 数组解析为内存数组时,没有构建地图的速度损失。如果您需要通过多个字段构建内存索引以进行快速访问,您可以在加载期间或之后进行。但是,如果您像以前一样存储 JSON,则您无法选择在不构建映射的情况下快速加载,因为 JSON 解析器将始终必须根据您的结构构建庞大的 id 映射。
Structure of how you store data in memory does not have to be (and should not be) the same as structure of storage on disk because there is no way to serialize/deserialize internal JavaScript map structure. If it was possible then you would serialize and store indexes just like MS SQL Server stores tables and indexes.
在内存中存储数据的结构不必(也不应该)与磁盘上的存储结构相同,因为无法序列化/反序列化内部 JavaScript 映射结构。如果可能,那么您将序列化和存储索引,就像 MS SQL Server 存储表和索引一样。
But if framework that you are using forces you to have same structure in memory and disk then I support your choice of using id as key in one big object, because then it's easier to pass id in JSON requests to and from server to do any action with email item or update it's state in UI, assuming that both server and browser keep significant list of email items in memory.
但是,如果您使用的框架强制您在内存和磁盘中具有相同的结构,那么我支持您选择使用 id 作为一个大对象中的键,因为这样更容易在 JSON 请求中传递 id 到服务器和从服务器执行任何操作使用电子邮件项目或更新它在 UI 中的状态,假设服务器和浏览器都在内存中保留重要的电子邮件项目列表。