pwm / jgami
在 JSON 上映射函数。
0.5.0
2018-10-26 19:22 UTC
Requires
- php: >=7.2.0
- pwm/treegami: ^1.0
Requires (Dev)
- infection/infection: ^0.8.2
- phpstan/phpstan: ^0.7.0
- phpunit/phpunit: ^6.1
- squizlabs/php_codesniffer: ^3.0
README
你是否曾经对列表中的函数进行过映射?现在你可以在 JSON 上做同样的操作!
JGami 提供了一个简单的 API,用于在保持结构完整性的同时更新任意复杂 JSON 结构中的值。
目录
需求
PHP 7.2+
安装
$ composer require pwm/jgami
用法
最简单的方法是直接查看一些示例代码。我们将通过映射函数来更新一些 JSON 数据,使其符合我们的喜好。
// What we have $json = '{ "name": "Alice", "age": 27, "likes": [ "Types", "Graphs", "Nature" ], "job": { "title": "Developer", "company": "Acme Corp." }, "pets": [ { "name": ["Woof"], "type": "Dog" }, { "name": ["Mr. Grumpy", "Mrs. Grumpy"], "type": "Cat" } ] }'; // What we want $expectedJson = '{ "name": "Alice Wonderland", "age": 37, "likes": [ "Types", "Trees", "Nature" ], "job": { "title": "Developer", "company": "Acme Corp." }, "pets": [ { "name": ["Woof <3"], "type": "Dog" }, { "name": ["Mr. Grumpy <3", "Mrs. Grumpy <3"], "type": "Cat" } ] }'; // Our update function, to be mapped over our JSON data // It takes a Node and return a JVal ie. a json value $f = function (Node $node): JVal { $jVal = $node->jVal(); if ($jVal->val() === 'Graphs') { // Replace "Graphs" with "Trees" $jVal = new JString('Trees'); } elseif ($node->key()->eq('age')) { // Add 10 to values with key "age" $jVal = new JInt($jVal->val() + 10); } elseif ($node->path()->hasAll('pets', 'name')) { // Add " <3" to values in paths with "pets" and "name" $jVal = new JString($jVal->val() . ' <3'); } elseif ($node->path()->hasNone('pets') && $node->key()->eq('name')) { // Add " Wonderland" to values with key "name" that has no "pets" in their path $jVal = new JString($jVal->val() . ' Wonderland'); } return $jVal; }; // true assert( json_encode(json_decode($expectedJson)) === json_encode(JGami::map($f, json_decode($json))) );
值的修改仅限于叶节点。这保留了结构的完整性。唯一的例外是扩展叶节点,如下面的示例所示。
$json = '{ "metadata": "To be filled" }'; $expectedJson = '{ "metadata": { "species": "Human", "planet": "Earth", "galacticLevel": 3, "note": "Observe only" } }'; $f = function (Node $node): JVal { $jVal = $node->jVal(); if ($node->key()->eq('metadata')) { // Metadata, provided by our galactic overlords $val = O::from([ 'species' => 'Human', 'planet' => 'Earth', 'galacticLevel' => 3, 'note' => 'Observe only', ]); // Replace the existing string value with the above object return new JObject($val); } return $jVal; }; // true assert( json_encode(json_decode($expectedJson)) === json_encode(JGami::map($f, json_decode($json))) );
这保留了现有的结构,同时通过新的子结构扩展了它。
工作原理
待定
测试
$ composer utest
$ composer phpcs
$ composer phpstan
$ composer infection