简体   繁体   中英

Expand nested JSONB data in SELECT query result

Assuming I have a table with JSONB data:

create table x (
  id integer primary key generated always as identity,
  name text,
  data jsonb
);

Assuming data can have nested data, I would like to display all data inside data to have this kind of result:

id  name  data.a  data.b.0  data.b.1  data.c
1   test  1       foo       bar       baz
2   test2 789     pim       pam       boom

Is there a way to do this without specifying all the JSONB properties names?

JSONB_TO_RECORDSET() function might be used within such a Select statement

SELECT a AS "data.a", 
      (b::JSONB) ->> 0 AS "data.b.0", (b::JSONB) ->> 1 AS "data.b.1",
       c AS "data.c"
  FROM x, 
       JSONB_TO_RECORDSET(data) AS j(a INT, b TEXT, c TEXT)
 ORDER BY id

Presuming you have such JSONB values in the data column

[ { "a": 1, "b": ["foo","bar"], "c": "baz" }]
[ { "a": 789, "b": ["pim","pam"], "c": "boom" }]

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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