postgres强制json数据类型

时间:2016-06-15 23:13:22

标签: json postgresql psql postgresql-9.4

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

感谢

1 个答案:

答案 0 :(得分: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}).
相关问题