我自己也遇到过这个问题,这就是我的处理方法。我创建了一个辅助函数,它遍历数组并使用 ->> 运算符使用下标来获取文本值。如果有人知道更好的方法,我很高兴听到,因为这似乎有点笨拙。
CREATE OR REPLACE FUNCTION json_text_array_to_pg_text_array(data json) returns text[] AS $$
DECLARE
i integer;
agg text[];
BEGIN
FOR i IN 0..json_array_length(data)-1 LOOP
agg := array_append(agg, data->>i);
END LOOP;
return agg;
END
$$ language plpgsql;
然后您可以执行以下操作:
test=# select json_text_array_to_pg_text_array('[ "hello","the\"re","i''m", "an", "array" ]'::json);
json_text_array_to_pg_text_array
----------------------------------
{hello,"the\"re",i'm,an,array}
(1 row)
如果您不想直接处理数组,也可以使函数只返回一组文本:
CREATE OR REPLACE FUNCTION json_text_array_to_row(data json) returns setof text AS $$
DECLARE
i integer;
BEGIN
FOR i IN 0..json_array_length(data)-1 LOOP
return next data->>i;
END LOOP;
return;
END
$$ language plpgsql;
然后这样做:
test=# select json_text_array_to_row('{"single_comment": "Fred said \"Hi.\"" ,"comments_array": ["Fred said \"Hi.\"", "Fred said \"Hi.\"", "Fred said \"Hi.\""]}'::json->'comments_array');
json_text_array_to_row
------------------------
Fred said "Hi."
Fred said "Hi."
Fred said "Hi."
(3 rows)