Skip to content
Database

pg_jsonschema:JSON 模式验证

JSON Schema 是一种用于注释和验证 JSON 文档的语言。pg_jsonschema 是一个 Postgres 扩展,它增加了使用 JSON Schema 文档验证 Postgres 内置 json 和 jsonb 数据类型的能力。

启用扩展 #

🌐 Enable the extension

  1. 在仪表板中转到数据库页面。
  2. 点击侧边栏的 扩展。
  3. 搜索 pg_jsonschema 并启用这个扩展。

函数 #

🌐 Functions

用法 #

🌐 Usage

由于 pg_jsonschema 将其实用工具暴露为函数,我们可以通过 select 语句来执行它们:

🌐 Since pg_jsonschema exposes its utilities as functions, we can execute them with a select statement:

select
extensions.json_matches_schema(
schema := '{"type": "object"}',
instance := '{}'
);

pg_jsonschema 通常会与 检查约束 一起使用,用来限制 json/b 列的内容以符合 JSON 模式。

create table customer(
id serial primary key,
...
metadata json,
check (
json_matches_schema(
'{
"type": "object",
"properties": {
"tags": {
"type": "array",
"items": {
"type": "string",
"maxLength": 16
}
}
}
}',
metadata
)
)
);
-- Example: Valid Payload
insert into customer(metadata)
values ('{"tags": ["vip", "darkmode-ui"]}');
-- Result:
-- INSERT 0 1
-- Example: Invalid Payload
insert into customer(metadata)
values ('{"tags": [1, 3]}');
-- Result:
-- ERROR: new row for relation "customer" violates check constraint "customer_metadata_check"
-- DETAIL: Failing row contains (2, {"tags": [1, 3]}).

资源 #

🌐 Resources