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:
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 Payloadinsert into customer(metadata)values ('{"tags": ["vip", "darkmode-ui"]}');-- Result:-- INSERT 0 1-- Example: Invalid Payloadinsert 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