philiprehberger/php-safe-json 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/php-safe-json

Composer 安装命令:

composer require philiprehberger/php-safe-json

包简介

Safe JSON parsing with exceptions, schema validation, and typed getters

README 文档

README

Tests Latest Version on Packagist Last updated

Safe JSON parsing with exceptions, schema validation, and typed getters.

Requirements

  • PHP 8.2+

Installation

composer require philiprehberger/php-safe-json

Usage

Decoding JSON

use PhilipRehberger\SafeJson\SafeJson;

$obj = SafeJson::decode('{"name":"Alice","age":30,"active":true}');

$obj->string('name');   // "Alice"
$obj->int('age');       // 30
$obj->bool('active');   // true

Dot Notation for Nested Access

$obj = SafeJson::decode('{"user":{"address":{"city":"Vienna"}}}');

$obj->string('user.address.city'); // "Vienna"
$obj->has('user.address.city');    // true
$obj->has('user.address.zip');     // false

Nested Objects

$obj = SafeJson::decode('{"user":{"name":"Alice"}}');

$user = $obj->object('user');
$user->string('name'); // "Alice"

Safe Decoding (No Exceptions)

$obj = SafeJson::tryDecode('{invalid}');
// Returns null instead of throwing

$obj = SafeJson::tryDecode('{"valid":true}');
// Returns JsonObject

Default Values

$obj = SafeJson::decode('{"name":"Alice"}');

$obj->get('name');              // "Alice"
$obj->get('missing', 'default'); // "default"
$obj->get('missing');           // throws JsonKeyException

Nullable Accessors

$obj = SafeJson::decode('{"name":"Alice","age":30}');

$obj->stringOrNull('name');    // "Alice"
$obj->stringOrNull('missing'); // null
$obj->intOrNull('name');       // null (wrong type)
$obj->intOrNull('age');        // 30

Merging Objects

$a = SafeJson::decode('{"name":"Alice","age":30}');
$b = SafeJson::decode('{"name":"Bob","email":"bob@example.com"}');

$merged = $a->merge($b);
$merged->string('name');  // "Bob" (overridden)
$merged->int('age');      // 30 (kept from $a)
$merged->string('email'); // "bob@example.com" (added from $b)

JSON Path Querying

$obj = SafeJson::decode('{"users":[{"name":"Alice","age":30},{"name":"Bob","age":25}]}');

$obj->query('$.users[*].name');       // ['Alice', 'Bob']
$obj->query('$.users[0].age');        // [30]
$obj->query('$..name');               // ['Alice', 'Bob'] (recursive descent)
$obj->query('$.users[0:1]');          // [['name' => 'Alice', 'age' => 30]]

Supported syntax: $ (root), .key (child), [0] (index), [*] (wildcard), ..key (recursive descent), [0:3] (slice), ['key'] (bracket notation).

JSON Diffing

$changes = SafeJson::diff(
    '{"name":"Alice","age":30}',
    '{"name":"Bob","age":30,"email":"bob@example.com"}'
);

// [
//   ['op' => 'replace', 'path' => 'name', 'value' => 'Bob', 'old' => 'Alice'],
//   ['op' => 'add', 'path' => 'email', 'value' => 'bob@example.com'],
// ]

Streaming Decode

// Memory-efficient decoding of large JSON arrays
foreach (SafeJson::decodeStream('/path/to/large-file.json') as $element) {
    // Each element is decoded one at a time
    // Only one element is held in memory
}

Encoding

$json = SafeJson::encode(['key' => 'value']);
// '{"key":"value"}'

$json = SafeJson::tryEncode($data);
// Returns null on failure instead of throwing

Serialization

$obj = SafeJson::decode('{"key":"value"}');

$obj->toArray(); // ['key' => 'value']
$obj->toJson();  // '{"key":"value"}'
json_encode($obj); // '{"key":"value"}' (JsonSerializable)
(string) $obj;     // '{"key":"value"}' (Stringable)

API

SafeJson

Method Description
decode(string $json): JsonObject Decode JSON string, throws JsonDecodeException on failure
tryDecode(string $json): ?JsonObject Decode JSON string, returns null on failure
encode(mixed $data, int $flags = 0): string Encode to JSON string, throws on failure
tryEncode(mixed $data, int $flags = 0): ?string Encode to JSON string, returns null on failure
diff(string $jsonA, string $jsonB): array Compare two JSON strings and return differences
decodeStream(string $filePath): Generator Stream-decode a JSON array file, yielding elements one at a time

JsonObject

Method Description
string(string $key): string Get string value by key
int(string $key): int Get integer value by key
float(string $key): float Get float value by key (accepts integers)
bool(string $key): bool Get boolean value by key
stringOrNull(string $key): ?string Get string value or null if missing/wrong type
intOrNull(string $key): ?int Get integer value or null if missing/wrong type
floatOrNull(string $key): ?float Get float value or null if missing/wrong type
boolOrNull(string $key): ?bool Get boolean value or null if missing/wrong type
array(string $key): array Get array value by key
object(string $key): JsonObject Get nested JsonObject by key
get(string $key, mixed $default = null): mixed Get value without type enforcement
has(string $key): bool Check if key exists
merge(self $other): self Merge with another JsonObject (other overrides on conflict)
query(string $path): array Query data using JSON Path expression
toArray(): array Return underlying array
toJson(int $flags = 0): string Return JSON string

All key-based methods support dot notation for nested access (e.g., user.address.city).

JsonPath

Method Description
query(array $data, string $path): array Query data using JSON Path expression

JsonDiff

Method Description
diff(mixed $a, mixed $b, string $path = ''): array Compare two values and return list of differences

StreamDecoder

Method Description
decodeStream(string $filePath): Generator Stream-decode a JSON array file element by element

Exceptions

Exception Thrown When
JsonDecodeException Invalid JSON input
JsonEncodeException Failed to encode data
JsonKeyException Missing key or type mismatch

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/php-safe-json 适用场景与选型建议

philiprehberger/php-safe-json 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「parse」 「encode」 「decode」 「typed」 「safe」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/php-safe-json 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/php-safe-json 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/php-safe-json 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 48
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 28
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-13