Search code examples
jsonpostgresqlplpython

Postgresql function plpython select json value


I'm using postgresql 9.6. I build a function where i do a "selec"t like :

id = TD["new"]["id"]
qry = plpy.prepare ("SELECT (decode->>'key')::integer AS key FROM table where id = $1;", ["int"])
res= plpy.execute(qry,[id])

The request work fine, but the result hold key and value, not only value. In fact, the result is like that : {"key":2937}

I want just the value.


Solution

  • The result object emulates a list or dictionary object. The result object can be accessed by row number and column name.

    create or replace function pf()
    returns integer as $$
    
        query = 'select 1 as key'
        rs = plpy.execute(query)
        plpy.notice(rs.__str__())
        return rs[0]['key']
    
    $$ language plpythonu;
    
    select pf();                                                                                  
    NOTICE:  <PLyResult status=5 nrows=1 rows=[{'key': 1}]>
     pf 
    ----
      1
    

    https://www.postgresql.org/docs/current/static/plpython-database.html