如何在Postgres中的嵌套json中查询对象 [英] How to query objects in nested json in postgres

查看:442
本文介绍了如何在Postgres中的嵌套json中查询对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个名为users的表,该表具有名为attrsjsonb列,其值如下:

Lets say I have table called users with jsonb column called attrs with values like this:

{
  "uuid5": {
    "label": "Email",
    "value": "example@test.com.tw"
  },
  "uuid6": {
    "label": "Last Name ",
    "value": "Yang"
  }
}

这里是单线:

"attrs": { "uuid5": { "label": "Email", "value": "example@test.com.tw" }, "uuid6": { "label": "Last Name ", "value": "Yang" }

如您所见,有uniq键uuid5uuid6等.

As you can see there are uniq keys uuid5, uuid6 and so on.

如何获得标签=电子邮件"且值="example@test.com.tw"的用户?

How to get users with label = 'Email' and value = 'example@test.com.tw'?

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

In postgres docs about json functions there is a function called jsonb_each which returns set of JSON object key/value pairs. But I could not find a way to write a query based on that.

推荐答案

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

You need jsonb_each to iterate over all entries in the attrs colum. It will return key/value pairs where the key is the uuid and the entry is your actual JSON structure you want to inspect. You can use that in conjunction with an EXISTS condition:

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' = 'example@test.com.tw')

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

这篇关于如何在Postgres中的嵌套json中查询对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆