我有一个具有以下架构的表(postgresql 14):
message sentiment classification
any text positive mobile, communication
message
只是字符串、短语。
sentiment
是一个字符串,只有一个单词
classification
是字符串,但可以有 1 到多个单词逗号分隔
我想用这些列创建一个 json 字段,如下所示:
{"msg":"any text", "sentiment":"positive","classification":["mobile,"communication"]}
此外,如果可能的话,有没有办法以这种方式考虑分类:
{"msg":"any text", "sentiment":"positive","classification 1":"mobile","classification 2" communication"}
最佳答案
问题的第一部分很简单 - Postgres 提供了分割字符串和转换为 json 的函数:
with t(message, sentiment, classification) as (values
('any text','positive','mobile, communication')
)
select row_to_json(x.*)
from (
select t.message
, t.sentiment
, array_to_json(string_to_array(t.classification, ', ')) as classification
from t
) x
第二部分更难 - 您希望 json 具有可变数量的属性,混合分组和非分组数据。我建议展开所有属性,然后将它们组装回来(请注意,如果您的真实表有 id,则实际上不需要编号的 CTE - 我只需要一些列来分组):
with t(message, sentiment, classification) as (values
('any text','positive','mobile, communication')
)
, numbered (id, message, sentiment, classification) as (
select row_number() over (order by null)
, t.*
from t
)
, extracted (id,message,sentiment,classification,index) as (
select n.id
, n.message
, n.sentiment
, l.c
, l.i
from numbered n
join lateral unnest(string_to_array(n.classification, ', ')) with ordinality l(c,i) on true
), unioned (id, attribute, value) as (
select id, concat('classification ', index::text), classification
from extracted
union all
select id, 'message', message
from numbered
union all
select id, 'sentiment', sentiment
from numbered
)
select json_object_agg(attribute, value)
from unioned
group by id;
关于sql - 如何在 Postgresql 中将字段转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72716821/