title: PostgreSQL Function: Return Multiple Rows as JSON
body: <p>I have a PostgreSQL function which successfully returns its data as</p>
  
  <pre><code>table(key character varying, value integer)
  </code></pre>
  
  <p>but I want to return JSON as it's more convenitent. I have looked at some other answers, and documentation, but it gets complicated when aliases are used (I'd like to return 'key' and 'value' as the column names).</p>
  
  <p>Can someone please recommend the most simple and concise way of expressing this function, in a way that does not require extra complexity to call:</p>
  
  <pre><code>DROP FUNCTION get_document_metadata_integer_records_by_document_id(integer);
  
  CREATE OR REPLACE FUNCTION get_document_metadata_integer_records_by_document_id(document_id integer)
    RETURNS table(key character varying, value integer) AS
  $BODY$
  
    SELECT document_metadata_records.key, document_metadata_integer_records.value FROM document_metadata_integer_records
    LEFT OUTER JOIN document_metadata_records
    ON document_metadata_integer_records.document_metadata_record_id = document_metadata_records.id
    WHERE document_metadata_records.document_id = $1
  
  $BODY$
    LANGUAGE sql VOLATILE
    COST 100;
  ALTER FUNCTION get_document_metadata_integer_records_by_document_id(integer)
    OWNER TO postgres;
  </code></pre>