[英]Function postgreSQL with JSON parameters
我必須創建一個 function,它采用這種類型的 object:
"users":"John",
"Level":"1",
"list":[
{"id":"1", "price1":"100.50", "price2":"90.50"},
{"id":"2", "price1":"100.60", "price2":"80.50"},
{"id":"2", "price1":"105.50", "price2":"700.50"}
]}
對於信息 JSON 沒有義務,但這對我來說似乎是最簡單的事情。 但也許創建 POSTGRES 類型可以工作。
如果我使用 JSON 或 PostGres 類型,那么如何處理 object。
CREATE OR REPLACE FUNCTION MYFUNCTION(myobject JSON ? CREATE TYPE ? )
RETURNS TABLE (
"OK" BOOLEAN,
"NB" VARCHAR
)
AS $$
DECLARE
BEGIN
-- I would like to get for each object in the list the price1 and price2 to
compare them.
END; $$
LANGUAGE 'plpgsql';
問題的關鍵似乎是如何從 json object 中提取值。這是一種方法:
select * from json_to_recordset('{
"users":"John",
"Level":"1",
"list":[
{"id":"1", "price1":"100.50", "price2":"90.50"},
{"id":"2", "price1":"100.60", "price2":"80.50"},
{"id":"2", "price1":"105.50", "price2":"700.50"}
]}'::json->'list') as foo(id int, price1 numeric, price2 numeric);
使用 json 變量而不是文字字符串:
select * from json_to_recordset(jsonvariable->'list') as foo(id int, price1 numeric, price2 numeric)
筆記。 您提供的json object不合法。 缺少一些逗號。 我還建議您使用 jsonb 而不是 json。
編輯:這是關於如何在 plpgsql function 中使用它的框架:
create or replace function func(jsonvariable json) returns table (ok boolean, nb text) as
$BODY$
declare
r record;
begin
for r in (select * from json_to_recordset(jsonvariable->'list') as foo(id int, price1 numeric, price2 numeric)) loop
--- DO THINGS
ok:=(r.price1>r.price2);
nb:='this is text returned';
return next;
end loop;
end;
$BODY$
language plpgsql;
No Need to use loop for processing on the JSON ARRAY. 您可以使用JSONB_ARRAY_ELEMENTS
或JSONB_TO_RECORDSET
來滿足您的要求,如下所示:
使用JSONB_TO_RECORDSET
CREATE OR REPLACE FUNCTION MYFUNCTION(myobject JSONB)
RETURNS TABLE (ok BOOLEAN, nb VARCHAR)
AS
$$
BEGIN
return query
select
price1>price2, -- you can change the condition here
id::varchar -- you can change the value as per your requirement
from jsonb_to_recordset(myobject ->'list') as x(id int, price1 numeric, price2 numeric);
END;
$$
LANGUAGE 'plpgsql';
使用JSONB_ARRAY_ELEMENTS
CREATE OR REPLACE FUNCTION MYFUNCTION1(myobject JSONB)
RETURNS TABLE (ok BOOLEAN, nb VARCHAR)
AS
$$
BEGIN
return query
select
(x->>'price1')::numeric > (x->>'price2')::numeric, -- you can change the condition here
(x->>'id')::varchar -- you can change the value as per your requirement
from jsonb_array_elements(myobject ->'list') as x;
END;
$$
LANGUAGE 'plpgsql';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.