webnium / json-pointer
基于 JSON Pointer (RFC6901) 的访问器实现
1.0.0
2013-11-29 14:31 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phake/phake: *
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-09-24 05:45:39 UTC
README
安装
此库通过 packagist.org 分发。
执行
$ wget https://getcomposer.org.cn/composer.phar $ php composer.phar require webnium/json-pointer:dev-master
或在您的 composer.json 中添加以下内容:
{ "require": { "webnium/json-pointer": "dev-master" } }
用法
ArrayAccessor
<?php $array = [ 'foo' => ['bar' => 1], 'list' => ['item0', 'item1'], ]; $accessor = new Webnium\JsonPointer\ArrayAccessor(new Webnium\JsonPointer\Parser); $accessor->set('/fizz/buzz', $array, 2); $accessor->set('/list/-', $array, 'item2'); echo '/foo/bar: ', var_export($accessor->get('/foo/bar', $array), true), PHP_EOL; echo '/fizz/buzz: ', var_export($accessor->get('/fizz/buzz', $array), true), PHP_EOL; echo '/list/0: ', var_export($accessor->get('/list/0', $array), true), PHP_EOL; echo '/list/2: ', var_export($accessor->get('/list/2', $array), true), PHP_EOL; echo 'root: ', var_export($accessor->get('', $array), true), PHP_EOL;
输出
/foo/bar: 1
/fizz/buzz: 2
/list/0: 'item0'
/list/2: 'item2'
root: array (
'foo' =>
array (
'bar' => 1,
),
'list' =>
array (
0 => 'item0',
1 => 'item1',
2 => 'item2',
),
'fizz' =>
array (
'buzz' => 2,
),
)
解析器
<?php use Webnium\JsonPointer\Parser; use Webnium\JsonPointer\Exception\ExceptionInterface as JsonPointerException; $parser = new Parser; $pointers = [ '/foo/bar', '/', '', '/foo/~01/~1', '/~a/aaa', 'foo' ]; foreach ($pointers as $pointer) { try { $parsed = $parser->parse($pointer); echo "$pointer: ", var_export($parsed, true), PHP_EOL; } catch (JsonPointerException $e) { echo "$pointer: ", 'thrown \'' . get_class($e) . '\' with message \'' . $e->getMessage() . '\'', PHP_EOL; } }
输出
/foo/bar: array (
0 => 'foo',
1 => 'bar',
)
/: array (
0 => '',
)
: array (
)
/foo/~01/~1: array (
0 => 'foo',
1 => '~1',
2 => '/',
)
/~a/aaa: thrown 'Webnium\JsonPointer\Exception\SyntaxError' with message 'unknown escape sequence "~a" detected.'
foo: thrown 'Webnium\JsonPointer\Exception\SyntaxError' with message 'pointer start with "f", "/" expected.'
许可证
此库在 MIT 许可证下分发。有关更多信息,请参阅 LICENSE 文件。