sintese / jsonflatten
v0.3.0
2023-10-04 00:58 UTC
Requires
- ext-json: *
- justinrainbow/json-schema: ^5.2
Requires (Dev)
- roave/security-advisories: dev-latest
This package is auto-updated.
Last update: 2024-09-04 19:43:38 UTC
README
针对由 json-schema 构建的对象的表格和扩展案例研究。
使用定义
给定一个由 json-schema 指定的对象定义
$schema = <<<JSON { "$schema": "https://json-schema.fullstack.org.cn/draft/2020-12/schema", "$id": "https://example.com/product.schema.json", "title": "Product", "description": "A product from Acme's catalog", "type": "object", "properties": { "productId": { "description": "The unique identifier for a product", "type": "integer" }, "dimensions": { "type": "object", "properties": { "width": { "type": "number" }, "height": { "type": "number" } } }, "tags": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" } } } } } } JSON
我们的目标是对其进行内容表格化,以简化其操作
echo (new SchemaFlatten())->flat(new SchemaObject($schema));
表格化的结构将包含在相同级别上的键(路径)和值(定义)
{ "$.productId": { "description": "The unique identifier for a product", "type": "integer", "path": "$.productId", "prop": "productId" }, "$.dimensions.width": { "type": "number", "path": "$.dimensions.width", "prop": "width" }, "$.dimensions.height": { "type": "number", "path": "$.dimensions.height", "prop": "height" }, "$.tags[0].name": { "type": "string", "path": "$.tags[0].name", "prop": "name" } }
拥有表格化结构后,我们可以创建一个扁平化的对象,从而简化其存储
$payload = <<<JSON { "$.productId": 1, "$.dimensions.width": 3, "$.dimensions.height": 6, "$.tags[0].name": "tag" } JSON;
该结构可以在稍后用于重新组合原始对象
echo (new SchemaFlatten())->unflat($payload);
因此,使用表格化时采用的 json schema 格式作为基础
{ "productId": 1, "dimensions": { "width": 3, "height": 6 }, "tags": [ { "name": "tag" } ] }
贡献
欢迎贡献、修正和建议。