【问题标题】:postgres force json datatypepostgres 强制 json 数据类型
【发布时间】:2016-06-15 23:13:21
【问题描述】:

使用 JSON 数据类型时,是否有办法确保输入 JSON 必须包含元素。我不是说主要的,我希望插入的 JSON 至少有 id 和 name 元素,它可以有更多但至少 id 和 name 必须在那里。

谢谢

【问题讨论】:

    标签: json postgresql psql postgresql-9.4


    【解决方案1】:

    该函数检查你想要什么:

    create or replace function json_has_id_and_name(val json)
    returns boolean language sql as $$
        select coalesce(
            (
                select array['id', 'name'] <@ array_agg(key)
                from json_object_keys(val) key
            ),
            false)
    $$;
    
    
    select json_has_id_and_name('{"id":1, "name":"abc"}'), json_has_id_and_name('{"id":1}');
    
     json_has_id_and_name | json_has_id_and_name 
    ----------------------+----------------------
     t                    | f
    (1 row) 
    

    您可以在检查约束中使用它,例如:

    create table my_table (
        id int primary key,
        jdata json check (json_has_id_and_name(jdata))
    );
    
    insert into my_table values (1, '{"id":1}');
    
    ERROR:  new row for relation "my_table" violates check constraint "my_table_jdata_check"
    DETAIL:  Failing row contains (1, {"id":1}).
    

    【讨论】:

    • 当有人更新时这会起作用吗?抱歉,我还没试过,等我到了我的车站,我会尝试的。
    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2020-09-01
    • 2014-08-02
    • 2020-08-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    相关资源
    最近更新 更多