flavioheleno / jay

json & simdjson 的轻量级封装

1.0.0 2023-08-17 20:12 UTC

This package is auto-updated.

Last update: 2024-09-17 22:28:53 UTC


README

Jay 是 json & simdjson 的轻量级封装,允许以透明的方式使用最快的可用 json 解码器。

在底层,如果可用并且 json 编码字符串不超过 4GiB(4.294.967.295 字节),Jay 将选择 simdjson,否则将回退到 PHP 的 JSON 核心扩展。

安装

要使用 Jay,只需简单运行

composer require flavioheleno/jay

用法

该库的使用非常简单。

$jsonEncoded = '{"a":"b","c":true,"d":10}';

// before
$jsonDecoded = json_decode($jsonEncoded, true);

// after
$jsonDecoded = Jay\Json::fromString($jsonEncoded, true);
// before
$jsonEncoded = filge_get_contents('path/to/file.json');
$jsonDecoded = json_decode($jsonEncoded, true);

// after
$jsonDecoded = Jay\Json::fromFile('path/to/file.json', true);

API

/**
 * @param string $path      Name of the file to read
 * @param bool $associative When true, JSON objects will be returned as associative arrays; when
 *                          false, JSON objects will be returned as an instance of stdClass
 * @param int $depth        Maximum nesting depth of the structure being decoded. The value must
 *                          be greater than 0, and less than or equal to 2.147.483.647
 *
 * @return array|stdClass Returns the value encoded in json as an appropriate PHP type; unquoted
 *                        values true, false and null are returned as true, false and null
 *                        respectively
 *
 * @throws InvalidArgumentException if the json cannot be decoded or if the encoded data is
 *                                  deeper than the nesting limit
 */
Jay\Json::fromFile(string $path, bool $associative = false, int $depth = 512): array|stdClass;


/**
 * @param string|Stringable $contents The json string being decoded; this function only works
 *                                    with UTF-8 encoded strings
 * @param bool $associative           When true, JSON objects will be returned as associative
 *                                    arrays; when false, JSON objects will be returned as an
 *                                    instance of stdClass
 * @param int $depth                  Maximum nesting depth of the structure being decoded. The
 *                                    value must be greater than 0, and less than or equal to
 *                                    2.147.483.647
 *
 * @return array|stdClass Returns the value encoded in json as an appropriate PHP type; unquoted
 *                        values true, false and null are returned as true, false and null
 *                        respectively
 *
 * @throws InvalidArgumentException if the json cannot be decoded or if the encoded data is
 *                                  deeper than the nesting limit.
 */
Jay\Json::fromString(
  string|Stringable $contents,
  bool $associative = false,
  int $depth = 512
): array|stdClass;

许可协议

该库采用MIT 许可协议