johnstevenson / json-works
创建、编辑、查询和验证 JSON
2.1.0
2023-04-17 13:36 UTC
Requires
- php: ^7.4 || ^8.0
- composer/pcre: ^3.1
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpstan/phpstan-strict-rules: ^1.1
- phpunit/phpunit: ^9.6.5
README
一个用于创建、编辑、查询和验证 JSON 的 PHP 库。
安装
使用以下命令安装最新版本
$ composer require johnstevenson/json-works
要求
- PHP 7.4 及以上版本,虽然使用最新版本的 PHP 强烈推荐。
使用方法
该库旨在用于复杂 JSON 结构或需要验证的 JSON 数据。完整的用法信息可以在 文档 中找到。
概述
Json-Works 允许您使用 JSON Pointer 语法创建、编辑和查询 JSON 数据。例如
<?php $document = new JohnStevenson\JsonWorks\Document(); $document->addValue('/path/to/array/-', ['firstName'=> 'Fred', 'lastName' => 'Blogg']); // prettyPrint $json = $document->toJson(true);
这将生成以下 JSON
{ "path": { "to": { "array": [ { "firstName": "Fred", "lastName": "Blogg" } ] } } }
您可以通过调用以下方法查询此值
$person = $document->getValue('/path/to/array/0');
并更新它
$document->addValue('/path/to/array/0/lastName', 'Bloggs');
并移动它
$document->moveValue('/path/to/array/0', '/users/-'); $document->tidy(); $json = $document->toJson(true);
最终得到
{ "users": [ { "firstName": "Fred", "lastName": "Bloggs" } ] }
然后删除它
$document->deleteValue('/users/0');
验证
Json-Works 包含了 JSON Schema 的实现,版本 4,允许您验证 JSON 数据。如果文档包含无效或缺失的数据值,验证将失败,并在 $document->getError()
中显示错误。
$document = new JohnStevenson\JsonWorks\Document(); $document->loadData('path/to/data.json'); $document->loadScheme('path/to/schema.json'); if (!$document->validate()) { $error = $document->getError(); }
您还可以在构建文档时验证数据。以下示例模式描述了一个包含对象的数组,这些对象的属性都是必需的,并且已定义了它们的类型。
// schemas can be very simple { "items": { "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" } }, "required": [ "firstName", "lastName" ] } }
现在您可以检查您的数据是否有效
$document->loadSchema($schema); $document->addValue('/-', ['firstName'=> 'Fred']); if (!$document->validate()) { $error = $document->getError(); # "Property: '/0'. Error: is missing required property 'lastName'" }
没有模式,任何值都可以添加到任何位置。
许可证
Json-Works 采用 MIT 许可证 - 详细信息请参阅 LICENSE
文件。