1

I'm trying to pass a json object from my python code with psycopg2 like this to a postgres stored procedure:

{
  "experience": null,
  "phoneNumber": [
    "091184xxx"
  ],
  "location": "tehran"
}

but this error occur:

ERROR: malformed array literal: "phoneNumbers" Detail: Array value must start with "{" or dimension information.

how can I fix this error?

UPDATE: here is my stored procedure:

CREATE OR REPLACE FUNCTION data(job_req JSONB)
  RETURNS VOID
AS $$
DECLARE

INSERT INTO "JobRequirements" (expertise,"phoneNumbers", "location")
  VALUES (
    job_req ->> 'expertise',
    job_req ->> 'phoneNumbers' :: VARCHAR [],
    job_req ->> 'location'
  );
END;
$$ LANGUAGE 'plpgsql';

and type of "phoneNumbers" column is varchar(255) []

3
  • Show us the insert query that runs from the procedure and the definition of the table being inserted. Commented Dec 11, 2018 at 7:44
  • i've been add them to question Commented Dec 11, 2018 at 8:13
  • I think you need to do sth. like this. If so, yes, it is lame... Commented Dec 11, 2018 at 10:09

1 Answer 1

2

You must extract the JSON array element as a text and convert it to a VARCHAR array before inserting.

CREATE OR REPLACE FUNCTION data(job_req JSONB)
  RETURNS VOID
AS $$
BEGIN
INSERT INTO "JobRequirements" (expertise,"phoneNumbers", "location")
  SELECT 
    job_req ->> 'expertise' ,
     array_agg(d.phonenumber::VARCHAR ) ,
    job_req ->> 'location' 
    FROM jsonb_array_elements_text(job_req->'phoneNumbers') as d(phonenumber);
END;
$$ LANGUAGE plpgsql;

Demo

Sign up to request clarification or add additional context in comments.

Comments

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.