简体   繁体   English

JSON object id为主键模式设计

[英]JSON object with id as primary key schema design

I want to use an ID as the primary key in a JSON object. This way all users in the list are unique.我想用一个ID作为JSON object中的主键。这样列表中的所有用户都是唯一的。

Like so:像这样:

{
    "user": [{
        "id": 1,
        "name": "bob"
    }]

}

In an application, I have to search for the id in all elements of the list 'user'.在应用程序中,我必须在列表“用户”的所有元素中搜索 id。

But I can also use the ID as an index to get easier access to a specific user.但我也可以使用 ID 作为索引来更轻松地访问特定用户。 Like so:像这样:

{
    "user": {
        "1": {
            "name": "bob"
        }
    }
}

In an application, I can now simply write user["3"] to get the correct user.在应用程序中,我现在可以简单地编写user["3"]来获取正确的用户。

What should I use?我应该使用什么? Are there any disadvantages to the second option?第二种选择有什么缺点吗? I'm sure there is a best practice.我确信有一个最佳实践。

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.在处理 web 数据时,你会经常看到第一种格式。 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.如果有很多数据,那么您将需要遍历所有记录以找到匹配的 id,因为您的数据是一个数组。 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.不过,您可以在您的 Id 前面加上一个 alpha 值,然后您可以在进行查找时添加前缀。 I have used k in this example but you can choose a prefix that makes sense for your data.我在此示例中使用了 k,但您可以选择对您的数据有意义的前缀。 I use this format when storing objects as the json binary data type in databases.在数据库中将对象存储为 json 二进制数据类型时,我使用这种格式。

{
    "user": {
        "k1": {
            "name": "bob"
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM