pg_jsonschema:JSON 模式验证
JSON Schema 是一种用于注释和验证 JSON 文档的语言。pg_jsonschema 是一个 Postgres 扩展,它增加了使用 JSON Schema 文档验证 Postgres 内置 json 和 jsonb 数据类型的能力。
启用扩展 #
🌐 Enable the extension
- 在仪表板中转到数据库页面。
- 点击侧边栏的 扩展。
- 搜索
pg_jsonschema并启用这个扩展。
函数 #
🌐 Functions
json_matches_schema(schema json, instance json):检查一个json实例 是否符合 JSON Schema 架构。jsonb_matches_schema(schema json, instance jsonb):检查一个jsonb实例 是否符合 JSON Schema 架构。
用法 #
🌐 Usage
由于 pg_jsonschema 将其实用工具暴露为函数,我们可以通过 select 语句来执行它们:
🌐 Since pg_jsonschema exposes its utilities as functions, we can execute them with a select statement:
1select2 extensions.json_matches_schema(3 schema := '{"type": "object"}',4 instance := '{}'5 );pg_jsonschema 通常会与 检查约束 一起使用,用来限制 json/b 列的内容以符合 JSON 模式。
1create table customer(2 id serial primary key,3 ...4 metadata json,56 check (7 json_matches_schema(8 '{9 "type": "object",10 "properties": {11 "tags": {12 "type": "array",13 "items": {14 "type": "string",15 "maxLength": 1616 }17 }18 }19 }',20 metadata21 )22 )23);2425-- Example: Valid Payload26insert into customer(metadata)27values ('{"tags": ["vip", "darkmode-ui"]}');28-- Result:29-- INSERT 0 13031-- Example: Invalid Payload32insert into customer(metadata)33values ('{"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