3

I have a table with field fields json[]. I have created a function to insert the record into that table and here is the call

select * from add('[{"name":"Yes","value":"yes"},{"name":"No","value":"no"},{"name":"Neutral","value":"neutral"}]') as result;

and here is the function itself

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$;

but this is showing

malformed array literal: "[{"name":"Yes","value":"yes"},{"name":"No","value":"no"},{"name":"Neutra

then I tried this

select * from add('{"name":"Yes","value":"yes"},{"name":"No","value":"no"},{"name":"Neutral","value":"neutral"}') as result;

and this insert statement in function like

insert into polls(fields) values(array([''||_fields||'']::json[]));

and this is showing

syntax error at or near "["
4
  • I'm not sure, but what is the function result type? is it missing in the declaration? Commented Aug 26, 2018 at 0:07
  • @Jay updated the question to add return type Commented Aug 26, 2018 at 6:13
  • json[] essentially never makes sense. Use a single JSON value that itself contains an array Commented Aug 26, 2018 at 6:32
  • @a_horse_with_no_name then how can i insert same data if i make it to jsonb object Commented Aug 26, 2018 at 7:14

1 Answer 1

2

I was missing " for each individual object. This is how to create json object

{"{\"name\":\"Yes\",\"value\":\"yes\"}","{\"name\":\"No\",\"value\":\"no\"}","{\"name\":\"Neutral\",\"value\":\"neutral\"}"}

so the final query is

select * from add('{"{\"name\":\"Yes\",\"value\":\"yes\"}","{\"name\":\"No\",\"value\":\"no\"}","{\"name\":\"Neutral\",\"value\":\"neutral\"}"}') as result;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.