How to convert json to composite type

I am trying to work again with postgres 9.4 and new json functions and may have encountered an error. The problem is that once I generated the json string via to_json (..), I cannot convert it back to the Composite type, because postgres cannot process the json array internally.

When I write it to postgres Notation, it works and I can even access all the fields inside the array.

Does anyone know a better desktop?

Example 1: composite type for json and back DROP TYPE IF EXISTS myType; CREATE TYPE myType AS (since TIMESTAMP, the words TEXT []);

DO $$
DECLARE
    _my_variable myType;
    _my_json JSON;
BEGIN
    _my_variable := ROW(now(),ARRAY['Here','is','a','List','of','Words']);
    _my_json := to_json(_my_variable);

    RAISE INFO 'how my json looks like: %', _my_json;
    --{"since":"2015-06-30T09:12:35.12346","word":["Here","is","a","List","of","Words"]}

    _my_variable := json_populate_record(NULL::myType,_my_json);

    --ERROR:  malformed array literal: "["Here","is","a","List","of","Words"]"
    --DETAIL:  "[" must introduce explicitly-specified array dimensions.
    --CONTEXT:  PL/pgSQL function inline_code_block line 13 at assignment
END $$; 

      

Example 2: json with postgres-notation like array to composite type

DO $$
DECLARE
    _my_variable myType;
    _my_json JSON;
BEGIN
    _my_json := '{"since":"2015-06-30T09:12:35.12346","words": "{Here,is,a,List,of,Words}" }';
    _my_variable := json_populate_record(NULL::myType,_my_json);
    RAISE INFO 'how my object looks like: %', _my_variable;
    RAISE INFO 'how my array looks like: %', _my_variable.words;
    --("2015-06-30 09:12:35.12346","{Here,is,a,List,of,Words}")
END $$; 

      

+3


source to share





All Articles