postgres force json 数据类型

postgres force json datatype

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

谢谢

函数检查你想要什么:

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}).