devlop / json
简单JSON包装器,提高处理json数据的体验
Requires
- php: ^7.4|^8.0
Requires (Dev)
- devlop/phpunit-exception-assertions: ^1.0
- phpunit/phpunit: ^9.5
- symfony/polyfill-php81: ^1.22
- symfony/var-dumper: ^5.2
README
Json
JSON包装器,提供比原生 json_encode
和 json_decode
更好的开发者体验。
安装
composer require devlop/json
与 json_encode / json_decode 的区别
- 出错时始终抛出
\JsonException
- 参数顺序一致(
$value
/$json
,$flags
,$depth
) - 编码和解码时更严格,只支持数组和对象,不支持标量值
用法
编码和解码都是静态方法,参数顺序相同:首先输入,然后是 int $flags
,最后是 int $depth
。
编码
encode
方法是对原生 json_encode 方法的包装。
签名: public static function encode(array|object $value, int $flags = 0, int $depth = 512) : string
use Devlop\Json\Json; $output = Json::encode($input); // or with flags $output = Json::encode($input, \JSON_HEX_TAG | \JSON_NUMERIC_CHECK);
编码(格式化打印)
pretty
方法是一个方便的方法,可以在不手动指定 JSON_PRETTY_PRINT
标志的情况下获取格式化的输出。
它具有与 encode()
相同的签名。
use Devlop\Json\Json; $output = Json::pretty($input); // or with flags $output = Json::encode($input, \JSON_HEX_TAG | \JSON_NUMERIC_CHECK);
解码
decode
方法是对原生 json_decode 方法的包装。
签名: public static function decode(string $json, int $flags = 0, int $depth = 512) : array|object
use Devlop\Json\Json; $output = Json::decode($input); // or with flags $output = Json::decode($input, \JSON_INVALID_UTF8_IGNORE);
解码(关联数组)
decodeAssoc
方法是一个方便的方法,用于解码但强制所有对象都转换为关联数组,而无需手动指定 JSON_OBJECT_AS_ARRAY
标志。
它具有与 decode()
相同的签名。
use Devlop\Json\Json; $output = Json::decodeAssoc($input); // or with flags $output = Json::decodeAssoc($input, \JSON_INVALID_UTF8_IGNORE);
错误处理
每次发生错误时都会抛出原生的 JsonException
。
支持的类型
我相信在PHP中JSON最常用的用法是存储数组或对象的JSON表示。确实,单个字符串、整数、布尔值或甚至是单个null值都是有效的JSON文档,但如果你像我一样,只使用JSON来存储数组或对象,那么将其他所有内容视为无效数据并抛出异常会更容易一些,这减少了在解码后检查类型的需要。
深度参数和 NO_FLAGS
如果你想在没有任何附加标志的情况下访问 $depth 参数,你必须为 $flags
参数提供默认值 0
,但为了让体验更清晰,你可以使用常量 Json::NO_FLAGS
。
$output = Json::encode($input, Json::NO_FLAGS, 3);