我正在尝试在Postgresql 9.3中使用新的
JSON功能,而我正在寻找一种能够使用JSON的功能,即to_json(anyelement)的对话.
以下是JSON示例:
{"single_comment": "Fred said \"Hi.\"","comments_array": ["Fred said \"Hi.\"","Fred said \"Hi.\"","Fred said \"Hi.\""]}
查询:
SELECT json_array_elements(json_column->'comments_array')
返回文档中描述的SET OF JSON.
"Fred said \"Hi.\"" "Fred said \"Hi.\"" "Fred said \"Hi.\""
有没有办法取消结果,所以我可以得到以下结果:
Fred said "Hi." Fred said "Hi." Fred said "Hi."
在文档中,我没有看到任何可以帮助我的功能.不幸的是,对我来说,不能选择PLV8.
任何想法都受到高度赞赏.
我自己也遇到过这个问题,这就是我接触它的方式.我创建了一个辅助函数,它迭代数组并使用 – >>运算符使用下标来获取文本值.如果有人知道更好的方式,我很高兴听到它,因为这看起来有点笨拙.
原文链接:/postgresql/452770.htmlCREATE 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,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.\"","Fred said \"Hi.\""]}'::json->'comments_array'); json_text_array_to_row ------------------------ Fred said "Hi." Fred said "Hi." Fred said "Hi." (3 rows)