如何查询jsonb的嵌套数组

时间:2019-10-09 15:04:52

标签: json postgresql

我正在使用一列嵌套的多个jsonb对象的PostgreSQL 11表

模拟问题:-

CREATE TABLE public.test
(
  id integer NOT NULL DEFAULT nextval('test_id_seq'::regclass),
  testcol jsonb
)
insert into test (testcol) values 
('[{"type": {"value": 1, "displayName": "flag1"}, "value": "10"},
{"type": {"value": 2, "displayName": "flag2"}, "value": "20"}, 
{"type": {"value": 3, "displayName": "flag3"}, "value": "30"},
 {"type": {"value": 4, "displayName": "flag4"}},
 {"type": {"value": 4, "displayName": "flag4"}},
 {"type": {"value": 6, "displayName": "flag6"}, "value": "40"}]');

我正在尝试:

  1. 如果type =特定值,则获取外部值。例如如果flag3在显示名称中,则获取值30。
  2. 计数内部json中flag4的出现

1 个答案:

答案 0 :(得分:1)

您可以使用json_to_recordset进行解析:

WITH cte AS (
  SELECT  test.id, sub."type"->'value' AS t_value, sub."type"->'displayName' AS t_name, value
  FROM test
  ,LATERAL jsonb_to_recordset(testcol) sub("type" jsonb, "value" int)
)
SELECT *
FROM cte
-- WHERE ...
-- GROUP BY ...;

db<>fiddle demo