databasepostgresqlstored-proceduresstored-functionsfunction-query

How to write a select function for converting table data to JSON?


I am using postgresql sp function for getting table data in JSON format. But i am getting this error.

structure of query does not match function result type DETAIL: Returned type json does not match expected type uuid in column 1. CONTEXT: SQL statement "SELECT array_to_json(array_agg(row_to_json(tech_alias))) FROM (select * from "Dcep"."Technologies") tech_alias" PL/pgSQL function "Dcep".jsontechnologies() line 3 at RETURN QUERY SQL state: 42804

I tried this function

CREATE OR REPLACE FUNCTION "Dcep".jsontechnologies()
RETURNS TABLE
(id uuid, technologyname text, 
technologytype text,
 status text,
createddate timestamp without time zone,
 createdby text, createdip text,
lastmodifieddate timestamp without time zone,
lastmodifiedby text,
 lastmodifiedip text, componentid uuid
) LANGUAGE 'plpgsql' AS 
$BODY$
BEGIN
RETURN Query 
SELECT array_to_json(array_agg(row_to_json(tech_alias)))
FROM (select * from "Dcep"."Technologies") tech_alias; END;
$BODY$; ALTER FUNCTION "Dcep".jsontechnologies() OWNER TO postgresql;

Solution

  • I got my error resolved, changed my query to this:

    select json_build_object('technologies', json_agg(techs)) technologies 
    from (
    select 
          t."Id",
          t."TechnologyName",
          t."TechnologyType", 
          t."Status", 
          t."ComponentID"
    from "Dcep"."Technologies" t
    )techs;