johnitvn/json-query

解析器,创建、编辑、查询和验证 JSON 文件。

1.0.2 2015-07-22 20:34 UTC

This package is auto-updated.

Last update: 2024-09-19 11:02:22 UTC


README

Latest Stable Version License Total Downloads Monthly Downloads Daily Downloads

一个用于解析、创建、编辑、查询和验证 JSON 的 PHP 库。

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一

php composer.phar require --prefer-dist johnitvn/json-query "*"

或者在您的 composer.json 文件的 require 部分添加

"johnitvn/json-query": "*"

使用方法

该库旨在用于嵌套的 JSON 结构或需要验证的 JSON 数据。或者在任何您觉得做以下事情更方便的情况下

$document = new johnitvn\jsonquery\JsonDocument();
$document->addValue('/path/to/nested/array/-', array('firstName'=> 'Fred', 'lastName' => 'Blogg'));
$json = $document->toJson(true);

这将给出以下 JSON

{
    "path": {
        "to": {
            "nested": {
                "array": [
                    {
                        "firstName": "Fred",
                        "lastName": "Blogg"
                    }
                ]
            }
        }
    }
}

您可以通过调用以下方式查询此值

$person = $document->getValue('/path/to/nested/array/0');

并更新它

$document->addValue('/path/to/nested/array/0/lastName', 'Bloggs');

并移动它

$document->moveValue('/path/to/nested/array/0', '/users/-');
$document->tidy();
$json = $document->toJson(true);

最终删除它

{
    "users": [
        {
            "firstName": "Fred",
            "lastName": "Bloggs"
        }
    ]
}

然后删除它

$document->deleteValue('/users/0');

Json Query 包含了 JSON Schema 的实现,版本 4。这允许您验证您的数据。以下示例模式描述了一个包含所有属性都必需且类型已定义的对象数组的模式。

$schema = '{
    "items": {
        "properties": {
            "firstName": {"type": "string"},
            "lastName": {"type": "string"}                  
        },
        "required": ["firstName", "lastName"]
    }
}';

现在当您尝试添加值时,Jquery Query 只会添加有效的值。所以您必须进行检查。

$document->loadSchema($schema);

$result = $document->addValue('/-', array('firstName'=> 'Fred', 'lastName' => 'Bloggs'));
# true

$result = $document->addValue('/-', array('firstName'=> 'Fred', 'lastName' => 3));
# false, lastName is not a string

$result = $document->addValue('/0', array('firstName'=> 'Fred'));
# true, required values are not checked when we are building

# but are checked if we validate directly

$result = $document->validate();
# false - required lastName is missing

没有模式,任何值都可以添加到任何地方,当然