我正在尝试使用psycopg2将我的python对象中的json对象传递给Postgres存储过程:
{
"experience": null,
"phoneNumber": [
"091184xxx"
],
"location": "tehran"
}
但是会发生此错误:
错误:格式不正确的数组文字:“ phoneNumbers”详细信息:数组值 必须以“ {”或尺寸信息开头。
如何解决此错误?
更新: 这是我的存储过程:
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';
“电话号码”列的类型为varchar(255) []
答案 0 :(得分:0)
在插入之前,您必须将JSON数组元素提取为文本并将其转换为VARCHAR
数组。
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;