ybushenko / json-parser
解析json
Requires
- guzzlehttp/guzzle: ^6.5
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is auto-updated.
Last update: 2024-09-25 20:07:22 UTC
README
Json-parser是一个通用的解析器,它通过特定的规则将json转换为PHP数组,数据源可以是文件、文本或url。
use JsonParser\Config; use JsonParser\JsonParser; use JsonParser\Rules\CallableRule; use JsonParser\Rules\DotPathRule; use JsonParser\Loader\TextLoader; $json = <<<JSON { "data": { "general": { "id": 12, "category": "Eat", "url": "/goods/category/eat" }, "goods": [ { "id":1, "names": { "ru_name":"Печенье", "en_name":"Cookie" }, "cost":12.5 },{ "id":2, "names": { "ru_name":"Молоко", "en_name":"Milk" }, "cost":17 },{ "id":3, "names": { "ru_name":"Яблоко", "en_name":"Apple" }, "cost":19 } ] } } JSON; $rules = [ 'ru_name' => new DotPathRule('names.ru_name'), 'en_name' => new DotPathRule('names.en_name'), 'custom' => new CallableRule(function ($item) { return $item['names']['ru_name'].$item['names']['en_name']; }) ]; $config = (new Config($rules)) ->setLoader(new TextLoader($json)) ->setBasePath('data.goods') ->setIgnoreErrors(true); $result = (new JsonParser($config))->parse(); var_dump($result);
结果
array(3) {
[0] => array(3) {
'ru_name' => string(14) "Печенье"
'en_name' => string(6) "Cookie"
'custom' => string(20) "ПеченьеCookie"
}
[1] => array(3) {
'ru_name' => string(12) "Молоко"
'en_name' => string(4) "Milk"
'custom' => string(16) "МолокоMilk"
}
[2] => array(3) {
'ru_name' => string(12) "Яблоко"
'en_name' => string(5) "Apple"
'custom' => string(17) "ЯблокоApple"
}
}
安装
composer require ybushenko/json-parser
数据源(Loader)
文本(TextLoader)
要使用文本数据源,只需在TextLoader
构造函数中将json作为文本传递
$loader = new JsonParser\Loader\TextLoader('[{"name": "a", "text": "foo"}, {"name": "b", "text": "bar"}]');
文件(FileLoader)
要使json从文件加载,需要将文件绝对路径传递给FileLoader
构造函数
$loader = new JsonParser\Loader\FileLoader(__DIR__ . '/data/goods.json');
Url(UrlLoader)
也可以通过url加载json,为此需要使用UrlLoader
。第二个参数可以传递一个与GuzzleHttp\ClientInterface
兼容的http请求客户端
$loader = new JsonParser\Loader\UrlLoader('http://url');
处理规则(Rules)
使用特殊规则可以将数据转换为数组,这些规则可以用来获取数据并将其转换为所需的类型
点路径(DotPathRule)
使用此规则时,解析器将尝试通过指定的路径获取数据。
$rule = new \JsonParser\Rules\DotPathRule('path.to.node');
数组规则(ArrayRule)
使用此规则时,解析器将尝试通过指定的路径获取数据,并将返回包含指定节点的数组数组的数组。
$rule = new \JsonParser\Rules\ArrayRule('path.to.nodes', ['node1', 'node2', 'node3']);
自定义处理(CallableRule)
可以使用CallableRule
进行自定义值处理。规则接受一个匿名函数,作为输入参数将整个目标对象传递,以便用户自行处理值。
$rule = new \JsonParser\Rules\CallableRule(function ($item) { return $item['node']; });
从字典(FromDictionaryRule)
要使用此规则,首先需要将字典添加到解析器对象中
$parser = new \JsonParser\JsonParser($config); $parser->addDictionary('name', [1 => 'foo', 2 => 'bar']);
方法addDictionary
的第一个参数是将来需要使用的字典名称,第二个参数可以是数组(如上面的示例)或字符串,其中包含通过点分隔的路径到json中的数组数据
$parser = new \JsonParser\JsonParser($config); $parser->addDictionary('name', 'path.to.categories');
在这种情况下,将使用整个json作为字典,更具体地说,是其指定的部分。为了使字典可供解析器使用,它应包含键-值。作为值,允许数组、对象和其他类型。
规则的使用方式
$rule = new \JsonParser\Rules\FromDictionaryRule('name', 'path.to.node_id');
首先,解析器将尝试从path.to.node_id
获取值,然后将其与字典中的值进行匹配。如果找到该值,则替换它。
还可以处理获取到的值(例如,删除前后空格),为此使用第三个参数,它接受一个匿名函数
$rule = new \JsonParser\Rules\FromDictionaryRule('name', 'path.to.node_id', function ($value) { return trim($value); });
设置
忽略错误(setIgnoreErrors)
默认情况下,为了检查数据完整性,如果未找到指定路径的节点,解析器将抛出异常。为了忽略此类错误,应使用设置setIgnoreErrors(true)
$config->setIgnoreErrors(true);
基本路径(setBasePath)
默认情况下,解析器期望json在根节点中有一个数组。可以使用setBasePath
方法更改此节点。此设置允许指定要解析的数据的路径。
$config->setBasePath('path.to.nodes');
指定路径的节点必须是数组。
附加
添加json而不使用加载器(setJson)
可以直接使用json,而不使用加载器。为此,可以使用setJson
方法
$parser->setJson('[{"name": "a", "text": "foo"}, {"name": "b", "text": "bar"}]');
添加“原始”json代码时,它仍然会像所有先前情况一样转换为数组,并应用基本路径(basePath),可以使用getOriginalJson
方法获取原始(完整)json。此方法也将返回数组