如果元素是PostgreSQL中的JSON字符串,则将元素动态转换为JSON数组

时间:2018-07-24 13:59:06

标签: sql json postgresql

基本上,我必须从具有可怕格式的JSON对象中选择一个值。该值可以是字符串或JSON数组,如果是数组,则应将其元素聚合为单个逗号分隔的字符串。

例如,我的表可能如下所示:

  id  |                 field
------+--------------------------------------
  1   |            {"key": "string"} 
---------------------------------------------
  2   |  {"key": ["array", "of", "strings"]}

,我需要一个类似

的结果
"string", 
"array, of, strings"

我正在使用以下查询:

SELECT my_table.id,
       array_to_string(ARRAY(SELECT json_array_elements_text(field -> json_object_keys(field))), ', '),
FROM my_table

将JSON数组聚合为一个字符串。但是,当值是字符串时,我得到了ERROR: cannot call json_array_elements_text on a scalar。 因此,下一步似乎是将值转换为JSON数组时的值(基本上只是将其用方括号括起来)。

我该怎么做?我查看了Postgres文档,但没有看到可转换为不同JSON类型的函数。

我正在使用PostgreSQL 10

1 个答案:

答案 0 :(得分:1)

with c(id,field) as (values(1,'{"key": "string"}'::json),(2, '{"key": ["array", "of", "strings"]}'))
, pg10 as (select id, case when json_typeof(field->'key') != 'array' then json_build_array(field->>'key') else field->'key' end field from c)
, m as (select id, json_array_elements_text(field) field from pg10)
select distinct id, string_agg(field,', ') over (partition by id) field from m;

正如您在评论中提到的那样,您需要采取额外的步骤将SRF从case中删除

https://www.db-fiddle.com/f/mr5rWGpC6xRoBvUKwR7RTN/0