简体   繁体   中英

Create view having nested json text from a table - Postgres

Say, I have the following postgres table,

> select * from t;
+----+---------+-----------+---------+---------+
| id | a       | b         | c       | d       |
+----+---------+-----------+---------+---------+
| 1  | value_a | value_b   | value_c | value_d |
+----+---------+-----------+---------+---------+
...
+----+---------+-----------+---------+---------+
|... | ...     | ...       | ...     | ...     |
+----+---------+-----------+---------+---------+

Now I want to create a view from this table which is capable of storing data of following format having nested json text.

And this should be grouped by id column.

{
  "id": 1,
  "a": "A",
  "x":"{\"k1\":\"value_b\",\"k2\":\"{\"k21\":\"value_c\",\"k22\":\"value_d\"}\"}"
}

I have no idea how can I achieve this. Anyone there to write me a postgres sql query for this.

You can use the json(b)_build_* functions to generate json(b):

create view myview as
select 
    id,
    a,
    jsonb_build_object(
        'k1', b,
        'k2', jsonb_build_object(
            'k21', c,
            'k22', d
        )
    ) as x
from mytable

If you want the whole row as a single json object:

create view myview as
select jsonb_build_object(
    'id', id
    'a', a,
     'x', jsonb_build_object(
        'k1', b,
        'k2', jsonb_build_object(
            'k21', c,
            'k22', d
        )
    )
) val
from mytable

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