adhocore / json-fixer
修复/修复截断的JSON数据
v1.0.1
2023-09-29 01:06 UTC
Requires
- php: >=5.4.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^4.8 || ^5.7 || ^6.5 || ^7.0 || ^8.0 || ^9.0
README
PHP库,通过在末尾填充上下文对应的值来修复截断的JSON数据。适用于PHP5.4或更高版本。
- 无依赖(无供应商膨胀)。
这是一个正在进行中的项目,可能不会涵盖所有边缘情况。 如果您尝试使用它,打开一些问题或贡献,那将非常棒。
安装
composer require adhocore/json-fixer
用法
use Ahc\Json\Fixer; $json = (new Fixer)->fix('{"a":1,"b":2'); // {"a":1,"b":2} $json = (new Fixer)->fix('{"a":1,"b":true,'); // {"a":1,"b":true} $json = (new Fixer)->fix('{"b":[1,[{"b":1,"c"'); // {"b":[1,[{"b":1,"c":null}]]} // For batch fixing, you can just reuse same fixer instance: $fixer = new Fixer; $fixer->fix('...'); $fixer->fix('...'); // ...
错误
如果存在错误并且修复程序由于某种原因无法修复JSON,它将抛出 RuntimeException
。您可以通过传递静默标志(fix()
的第二个参数)来禁用此行为,在这种情况下,将返回原始输入
(new Fixer)->silent()->fix('invalid'); // 'invalid' (new Fixer)->silent(true)->fix('invalid'); // 'invalid' (new Fixer)->silent(false)->fix('invalid'); // RuntimeException
缺失值
默认情况下,缺失值用 null
填充。您可以通过传递所需的值到 missingValue()
来更改它
// key b is missing value and is padded with `null` $json = (new Fixer)->fix('{"a":1,"b":'); // {"a":1,"b":null} // key b is missing value and is padded with `true` $json = (new Fixer)->missingValue(true)->fix('{"a":1,"b":'); // {"a":1,"b":true} // key b is missing value and is padded with `"truncated"` // Note that you can actually inject a whole new JSON subset as 3rd param // but that should be a valid JSON segment and is not checked by fixer. $json = (new Fixer)->missingValue('"truncated"')->fix('{"a":1,"b":'); // {"a":1,"b":"truncated"}
待办事项
- 根据上下文可配置的缺失值(选项)