json - 如何在postgres中查询嵌套json中的对象

标签 json postgresql jsonb postgresql-9.6

假设我有一个名为 users 的表,其中包含名为 attrsjsonb 列,其值如下:

{
  "uuid5": {
    "label": "Email",
    "value": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debba6bfb3aeb2bb9eaabbadaaf0bdb1b3f0aaa9" rel="noreferrer noopener nofollow">[email protected]</a>"
  },
  "uuid6": {
    "label": "Last Name ",
    "value": "Yang"
  }
}

这里有一句台词:

"attrs": { "uuid5": { "label": "Email", "value": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305548515d405c5570445543441e535f5d1e4447" rel="noreferrer noopener nofollow">[email protected]</a>" }, "uuid6": { "label": "Last Name ", "value": "Yang" }

如您所见,有 uniq 键 uuid5uuid6 等。

如何获取标签 = 'Email' 且值 = ' [email protected] 的用户'?

postgres docs关于 json 函数,有一个名为 jsonb_each 的函数它返回一组 JSON 对象键/值对。但我找不到基于此编写查询的方法。

最佳答案

您需要 jsonb_each 来迭代 attrs 列中的所有条目。它将返回键/值对,其中键是 uuid,条目是您要检查的实际 JSON 结构。您可以将其与 EXISTS 条件结合使用:

select u.*
from users u
where exists (select *
              from jsonb_each(u.attrs) as t(uid,entry)
              where t.entry ->> 'label' = 'Email'
                and t.entry ->> 'value' = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f7eaf3ffe2fef7d2e6f7e1e6bcf1fdffbce6e5" rel="noreferrer noopener nofollow">[email protected]</a>')

在线示例:https://rextester.com/SHN95362

关于json - 如何在postgres中查询嵌套json中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55512016/

相关文章:

json - Django/PostgresQL jsonb (JSONField) - 将选择和更新转换为一个查询

string - 在 PostgreSQL 中获取 JSONB 的紧凑版本

javascript - DB 和 D3 通过 php 连接。无法完成 D3noob 的教程

javascript - 解析有效 JSON 字符串时遇到问题

ios - 当对象包含其他对象的数组时,如何解析 JSON?

postgresql - Postgres 事务似乎无缘无故采用 AccessExclusiveLock

java - Gson反序列化: How to distinguish between fields that are missing and fields that are explicitly set to null?

sql - 根据列中的重复项选择行

sql - PostgreSQL 8.2.9 枚举类型

json - 在 Postgresql 中查询复杂 JSON 的简洁方法