我有一个带有字段fields json[]
的表。我创建了一个将记录插入到该表中的函数,这是调用
select * from add('[{"name":"Yes","value":"yes"},{"name":"No","value":"no"},{"name":"Neutral","value":"neutral"}]') as result;
这是函数本身
CREATE OR REPLACE FUNCTION public.add(
_fields json[]) RETURNS SETOF json
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
query text;
BEGIN
insert into my_table(fields)
values(_fields);
query = 'SELECT json_build_object(''message'', ''Added.'')';
RETURN QUERY EXECUTE query;
END;
$BODY$;
但这显示
malformed array literal: "[{"name":"Yes","value":"yes"},{"name":"No","value":"no"},{"name":"Neutra
然后我尝试了
select * from add('{"name":"Yes","value":"yes"},{"name":"No","value":"no"},{"name":"Neutral","value":"neutral"}') as result;
以及类似函数中的该插入语句
insert into polls(fields) values(array([''||_fields||'']::json[]));
这正在显示
syntax error at or near "["
答案 0 :(得分:1)
我缺少每个单独对象的"
。这是创建json对象的方法
{"{\"name\":\"Yes\",\"value\":\"yes\"}","{\"name\":\"No\",\"value\":\"no\"}","{\"name\":\"Neutral\",\"value\":\"neutral\"}"}
所以最终查询是
select * from add('{"{\"name\":\"Yes\",\"value\":\"yes\"}","{\"name\":\"No\",\"value\":\"no\"}","{\"name\":\"Neutral\",\"value\":\"neutral\"}"}') as result;