如何将json转换为复合类型

时间:2015-06-30 07:26:12

标签: json postgresql

我正在尝试再次使用postgres 9.4和新的json功能,可能遇到了一个bug。问题是,一旦我通过to_json(..)生成了json-string,我就无法将其转换回Composite类型,因为postgres无法处理内部的json数组。

当我用postgres Notation写它时,它可以工作,我甚至可以访问数组中的所有字段。

有谁知道更好的工作环境?

示例1:复合类型为json和back     DROP TYPE IF EXISTS myType;     CREATE TYPE myType AS(         从TIMESTAMP开始,         单词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 $$; 

示例2:带有postgres-notation的json,如数组到复合类型

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 $$; 

0 个答案:

没有答案