Search code examples
sqljsondatabasepostgresqlsql-view

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.


Solution

  • 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