JSON对象具有ID作为主要键模式设计
我想将ID用作JSON对象中的主要键。这样,列表中的所有用户都是唯一的。
像这样:
{
"user": [{
"id": 1,
"name": "bob"
}]
}
在应用程序中,我必须在列表“用户”的所有元素中搜索ID。
但是我也可以将ID用作索引,以更轻松地访问特定用户。 像这样:
{
"user": {
"1": {
"name": "bob"
}
}
}
在应用程序中,我现在可以简单地编写用户[“ 3”]
获得正确的用户。
我应该使用什么?第二种选项有任何缺点吗?我确定有一个最佳练习。
I want to use an ID as the primary key in a JSON object. This way all users in the list are unique.
Like so:
{
"user": [{
"id": 1,
"name": "bob"
}]
}
In an application, I have to search for the id in all elements of the list 'user'.
But I can also use the ID as an index to get easier access to a specific user.
Like so:
{
"user": {
"1": {
"name": "bob"
}
}
}
In an application, I can now simply write user["3"]
to get the correct user.
What should I use? Are there any disadvantages to the second option? I'm sure there is a best practice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您想要的对象的外观,您想在对象上进行多少处理以及拥有多少数据。
处理Web数据时,您通常会看到第一种格式。如果有很多数据,那么您需要迭代所有记录以查找匹配ID,因为数据是一个数组。通常,该查询会在您的较低级别数据集上强制执行,因此可能已经索引了(例如,如果是数据库),因此这可能不是问题。这种格式是干净的,很容易绑定。
当您需要查找效率时,您的第二个选项效果最好,因为您的字典具有键值对,可以在大型数据集中更快地查找。所有库都不支持放置数字键(即使您强迫它是字符串)。您可以将ID带有Alpha值的前缀,然后您可以在查找时只添加前缀即可。我在此示例中使用了K,但是您可以选择一个对数据有意义的前缀。将对象作为数据库中的JSON二进制数据类型时,我会使用此格式。
It depends on what format you want objects to look like, how much processing you want to do on your objects and how much data you have.
When dealing with web data you will often see the first format. If there is a lot of data then you will need to iterate through all records to find your matching id because your data is an array. Often that query would be enforced on your lower level data set though so it might already be indexed (eg. if it is a database) so this may not be an issue. This format is clean and binds easily.
Your second option works best when you need efficiency in your lookups since you have a dictionary with key value pairs allowing for significantly faster lookups in large datasets. Putting a numeric key (even though you are forcing it to be a string) is not supported by all libraries. You can prefix your Id with an alpha value though, then you can just add the prefix when doing a lookup. I have used k in this example but you can choose a prefix that makes sense for your data. I use this format when storing objects as the json binary data type in databases.