简体   繁体   中英

JSON Schema validation in PostgreSQL?

我在PostgreSQL中找不到有关JSON模式验证的任何信息,有没有办法在PostgreSQL JSON数据类型上实现JSON模式验证?

There is a PostgreSQL extension that implements JSON Schema validation in PL/PgSQL.

It is used like this (taken from the project README file):

CREATE TABLE example (id serial PRIMARY KEY, data jsonb);
ALTER TABLE example ADD CONSTRAINT data_is_valid CHECK (validate_json_schema('{"type": "object"}', data));

INSERT INTO example (data) VALUES ('{}');
-- INSERT 0 1

INSERT INTO example (data) VALUES ('1');
-- ERROR:  new row for relation "example" violates check constraint "data_is_valid"
-- DETAIL:  Failing row contains (2, 1).

There is another PostgreSQL extension that implements json validation. The usage is almost the same as "Postgres-JSON-schema"

CREATE TABLE example (id serial PRIMARY KEY, data jsonb);
-- do is_jsonb_valid instead of validate_json_schema
ALTER TABLE example ADD CONSTRAINT data_is_valid CHECK (is_jsonb_valid('{"type": "object"}', data));

INSERT INTO example (data) VALUES ('{}');
-- INSERT 0 1

INSERT INTO example (data) VALUES ('1');
-- ERROR:  new row for relation "example" violates check constraint "data_is_valid"
-- DETAIL:  Failing row contains (2, 1).

I've done some benchmarking validating tweets and it is 20x faster than "Postgres-JSON-schema", mostly because it is written in C instead of SQL.

Disclaimer, I've written this extension.

What you need is something to translate JSON Schema constraints into PostgreSQL ones, eg:

{
    "properties": {
        "age": {"minimum": 21}
    },
    "required": ["age"]
}

to:

SELECT FROM ...
WHERE (elem->>'age' >= 21)

I'm not aware of any existing tools. I know of something similar for MySQL which might be useful for writing your own, but nothing for using the JSON type in PostgreSQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM