简体   繁体   中英

postgres return json from a function

I got to know that I can use row_to_json to return json output

For example If my query is:

select * from sample;

I can rewrite it as follows to return json output:

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. 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. You can't use plain SELECT in a PL/PgSQL function, it has to be SELECT INTO , RETURN QUERY SELECT , or PERFORM . Per the HINT error.

In your case all you need is a plain SQL function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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