[英]Create view having nested json text from a table - Postgres
Say, I have the following postgres table,说,我有以下 postgres 表,
> 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.现在我想从这个表创建一个视图,它能够存储具有嵌套 json 文本的以下格式的数据。
And this should be grouped by id
column.这应该按
id
列分组。
{
"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.
任何人都可以为此写一个 postgres sql 查询。
You can use the json(b)_build_*
functions to generate json(b):您可以使用
json(b)_build_*
函数来生成 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:如果您希望整行作为单个 json 对象:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.