sql - 如何在 Postgresql 中将字段转换为 JSON

标签 sql postgresql

我有一个具有以下架构的表(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;

DB fiddle

关于sql - 如何在 Postgresql 中将字段转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72716821/

相关文章:

sql - ORA-01749 : you may not GRANT/REVOKE privileges to/from yourself

c# - 更改datagridview日期列上的日期时间显示格式

sql - 非常大的 "delete from"语句与 "where"关闭,我应该优化吗?

macos - Postgresql 和 unicode 表名 : Why can I not select the table name from the information schema when it contains unicode characters?

json - 如何在数据库中定义和存储数据结构属性

sql - 如何在 PostgreSQL 查询中声明变量

sql - 有没有办法在 Visual Studio 中将 SQL 脚本导入 MDF 数据库?

SQL:主键列。人工 "Id"列与 "Natural"列

sql - 具有多个命令的规则

mysql - 查找具有特定值的所有关联的记录