简体   繁体   English

postgres从函数返回json

[英]postgres return json from a function

I got to know that I can use row_to_json to return json output 我知道我可以使用row_to_json来返回json输出

For example If my query is: 例如,如果我的查询是:

select * from sample;

I can rewrite it as follows to return json output: 我可以按如下方式重写它以返回json输出:

select row_to_json(sample) from sample;

But one thing I am trying to achieve is the same functionality in the function. 但我想要实现的一件事是功能中的相同功能。

To give you an example, here is the function returning table: 举个例子,这里是函数返回表:

CREATE FUNCTION find_val(val text) 
RETURNS SETOF sample AS
$$
BEGIN
RETURN QUERY
SELECT * FROM sample where $1 = ANY(col4);
END;
$$
LANGUAGE 'plpgsql';

Now instead of rows, I want to return JSON output from my function. 现在我想从函数返回JSON输出而不是行。 How can I do that ? 我怎样才能做到这一点 ?

Here is what I have tried so far: 这是我到目前为止所尝试的:

native=> CREATE FUNCTION find_val(val text) 
RETURNS SETOF sample AS
$$
BEGIN
RETURN QUERY
SELECT row_to_json(sample) FROM sample where $1 = ANY(col4) ; 
END;
$$
LANGUAGE 'plpgsql';
CREATE FUNCTION
native=> select find_val('yo');
ERROR:  structure of query does not match function result type
DETAIL:  Returned type json does not match expected type integer in column 1.
CONTEXT:  PL/pgSQL function find_val(text) line 3 at RETURN QUERY
native=> drop function find_val(text);
DROP FUNCTION



native=> CREATE FUNCTION find_val(val text) 
native-> RETURNS json AS
native-> $$
native$> BEGIN
native$> SELECT row_to_json(sample) FROM sample where $1 = ANY(col4);
native$> END;
native$> $$
native-> LANGUAGE 'plpgsql';
CREATE FUNCTION
native=> select find_val('yo');
ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function find_val(text) line 3 at SQL statement
native=> 

This is nothing to do with json vs other return types. 这与json vs其他返回类型无关。 You can't use plain SELECT in a PL/PgSQL function, it has to be SELECT INTO , RETURN QUERY SELECT , or PERFORM . 你不能在PL / PgSQL函数中使用普通的SELECT ,它必须是SELECT INTORETURN QUERY SELECTPERFORM Per the HINT error. 根据HINT错误。

In your case all you need is a plain SQL function. 在您的情况下,您只需要一个简单的SQL函数。

CREATE FUNCTION find_val(val text) 
RETURNS json AS
$$
SELECT row_to_json(sample) FROM sample where $1 = ANY(col4);
$$ LANGUAGE sql;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM