psx/json

通过 JSON-Patch/Pointer 读取和转换 JSON 文档

v3.0.2 2024-05-10 17:25 UTC

This package is auto-updated.

Last update: 2024-09-10 18:10:17 UTC


README

关于

一个包含处理 JSON 数据类库的库。它实现了 JSON patch 和 pointer 规范,并提供了一个简单的 JSON RPC 服务器。

使用方法

Patch/Pointer

<?php

$document = Document::from(\json_decode(\file_get_contents('/test.json')));
// or
$document = Document::from(\json_decode('{"author": {"name": "foo"}}'));

// get a value through a json pointer
$name = $document->pointer('/author/name');

// compare whether this document is equal to another document
$document->equals(['foo' => 'bar']);

// apply patch operations on the document
$document->patch([
    (object) ['op' => 'add', 'path' => '/author/uri', 'value' => 'http://google.com'],
]);

// convert the document back to a json string
echo $document->toString();

RPC 服务器

以下示例展示了使用纯 PHP 的一个超级简单的 JSON RPC 服务器。它也很容易集成到任何现有的框架中。

<?php

use PSX\Json\RPC\Server;
use PSX\Json\RPC\Exception\MethodNotFoundException;

$server = new Server(function($method, $arguments){
    if ($method === 'sum') {
        return array_sum($arguments);
    } else {
        throw new MethodNotFoundException('Method not found');
    }
});

$return = $server->invoke(\json_decode(file_get_contents('php://input')));

header('Content-Type: application/json');
echo \json_encode($return, JSON_PRETTY_PRINT);