Skip to content
Database

pg_jsonschema:JSON 模式验证

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

启用扩展 #

🌐 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:

1
select
2
extensions.json_matches_schema(
3
schema := '{"type": "object"}',
4
instance := '{}'
5
);

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

1
create table customer(
2
id serial primary key,
3
...
4
metadata json,
5
6
check (
7
json_matches_schema(
8
'{
9
"type": "object",
10
"properties": {
11
"tags": {
12
"type": "array",
13
"items": {
14
"type": "string",
15
"maxLength": 16
16
}
17
}
18
}
19
}',
20
metadata
21
)
22
)
23
);
24
25
-- Example: Valid Payload
26
insert into customer(metadata)
27
values ('{"tags": ["vip", "darkmode-ui"]}');
28
-- Result:
29
-- INSERT 0 1
30
31
-- Example: Invalid Payload
32
insert into customer(metadata)
33
values ('{"tags": [1, 3]}');
34
-- Result:
35
-- ERROR: new row for relation "customer" violates check constraint "customer_metadata_check"
36
-- DETAIL: Failing row contains (2, {"tags": [1, 3]}).

资源 #

🌐 Resources