【问题标题】:Postgres array of JSON avoid castingJSON的Postgres数组避免强制转换
【发布时间】:2013-08-07 09:24:19
【问题描述】:

在 PostgresSQL 9.2 上发布以下内容:

CREATE TABLE test (j JSON, ja JSON[]);
INSERT INTO test (j) VALUES('{"name":"Alex", "age":20}' ); -- Works FINE
INSERT INTO test (ja) VALUES( ARRAY['{"name":"Alex", "age":20}', '{"name":"Peter", "age":24}'] ); -- Returns ERROR

第一个插入工作正常。 第二次插入返回错误:column "ja" is of type json[] but expression is of type text[]

我可以转换类型来防止错误:

INSERT INTO test(ja) VALUES( CAST (ARRAY['{"name":"Alex", "age":20}', '{"name":"Peter", "age":24}'] as JSON[]) ); -- Works FINE

我的问题是是否有办法避免强制转换?

【问题讨论】:

    标签: arrays json postgresql


    【解决方案1】:
    insert into test(ja) values
    ('{"{\"name\":\"alex\", \"age\":20}", "{\"name\":\"peter\", \"age\":24}"}');
    

    为了避免混淆转义转换每个字符串:

    insert into test(ja) values
    (array['{"name":"alex", "age":20}'::json, '{"name":"peter", "age":24}'::json]);
    

    或者只是转换数组本身:

    insert into test (ja) values
    (array['{"name":"alex", "age":20}', '{"name":"peter", "age":24}']::json[]);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多