JSON output in Postgresql

后端 未结 4 1161
情深已故
情深已故 2020-12-31 15:18

I hope I am not missing something very obvious here,
I want to get JSON output from a postgres function (I imagine many other had already needed this) and I\'d be happy

相关标签:
4条回答
  • 2020-12-31 15:37

    There is built-in support for JSON since PostgreSQL 9.2 and it has increased with many other features in more recent versions(For example: JSON functions in PostgreSQL 0.4).

    Specially the row_to_json converts a record into a JSON object and the array_to_json turns arrays into JSON arrays.

    For example, both functions can be combined to easily turn the results of a SELECT query into JSON:

    SELECT array_to_json(array_agg(row_to_json(t))) FROM 
        (SELECT col1, col2, col3 FROM example_table) t
    
    0 讨论(0)
  • 2020-12-31 15:42

    On the server install:
    sudo apt-get install postgresql-plpython-9.4

    Then on your Postgres server:

    CREATE EXTENSION IF NOT EXISTS plpythonu;
    CREATE LANGUAGE plpythonu;
    
    CREATE OR REPLACE FUNCTION prettyprint_json(data text)
     RETURNS json
     AS $$
        import json
        return json.dumps(json.loads(data), indent=4)
     $$ LANGUAGE plpythonu;
    
    0 讨论(0)
  • 2020-12-31 15:49

    Use record_to_json(...) from 9.2, now available backported to 9.1.

    0 讨论(0)
  • 2020-12-31 15:50

    The postgresql plpython plugin certainly lets you do this using the python json library.

    You can do something like this:

    CREATE OR REPLACE FUNCTION myschema.tojsonfunc()
    AS $$    
    
       import json;
       jsonStr = json.dumps(myrecord)
    
    $$ LANGUAGE plpythonu;
    
    0 讨论(0)
提交回复
热议问题