定制 iliaal/fastjson 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

iliaal/fastjson

Composer 安装命令:

pie install iliaal/fastjson

包简介

Fast JSON encode/decode/validate for PHP 8.1+, backed by yyjson. Drop-in alternative to ext/json with namespaced fastjson_* functions and json_last_error-compatible error reporting.

README 文档

README

Tests Windows Build Version License: BSD-3-Clause Follow @iliaa

fastjson: 6x encode, 2.7x decode, 5x validate vs ext/json

Fast JSON encode, decode, and validate for PHP 8.1+. Drop-in alternative to ext/json with a namespaced fastjson_* API and json_last_error-compatible error reporting. Backed by yyjson 0.12.0, one of the fastest portable JSON libraries. Coexists with ext/json; adoption is opt-in per call site.

Status: pre-release. yyjson 0.12.0 is vendored and linked. The fastjson_encode / fastjson_decode / fastjson_validate trio plus fastjson_last_error / _msg / _pos / _info, the file helpers fastjson_file_decode / fastjson_file_encode, and the JSON Pointer / patch helpers fastjson_pointer_get / _exists / _set (RFC 6901) and fastjson_merge_patch (RFC 7386) are available. The compat harness against php-src/ext/json/tests/*.phpt passes everything targeting features fastjson aims to mirror; the rest is categorized in tests/upstream-json/.skiplist.

📦 Install

# PIE (PHP Foundation's extension installer; uses the composer.json
# at the repo root with type: "php-ext")
pie install iliaal/fastjson

On a minimal PHP image (e.g. php:8.x-cli from Docker Hub), PIE needs a few build tools installed first:

# Debian/Ubuntu
sudo apt install -y git bison libtool-bin

# macOS
brew install bison libtool

From source

git clone https://github.com/iliaal/fastjson.git
cd fastjson
phpize && ./configure --enable-fastjson
make -j
sudo make install
echo 'extension=fastjson.so' | sudo tee /etc/php/conf.d/fastjson.ini

Windows binaries

Pre-built 64-bit DLLs for PHP 8.1 through 8.5 (TS/NTS) are attached to each GitHub release.

🛠️ Usage

$json = fastjson_encode(['hello' => 'world']);     // string|false
$data = fastjson_decode($json, assoc: true);        // mixed
$ok   = fastjson_validate($json);                   // bool

if ($data === null && fastjson_last_error() !== 0) {
    fwrite(STDERR, fastjson_last_error_msg());
}

Function signatures track ext/json so call sites migrate by search-and-replace from json_* to fastjson_*. PHP 8.4 property hooks and JsonSerializable are honored.

Encode flags: JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_FORCE_OBJECT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_NUMERIC_CHECK, JSON_PRESERVE_ZERO_FRACTION, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_THROW_ON_ERROR.

Decode flags: JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_THROW_ON_ERROR, and the fastjson-only FASTJSON_DECODE_RELAXED (tolerates the JSONC subset ext/json rejects: // and /* */ comments, trailing commas, and a leading UTF-8 BOM).

Validate flags: JSON_INVALID_UTF8_IGNORE (other bits raise ValueError per ext/json's contract).

Beyond the core trio: fastjson_file_decode() / fastjson_file_encode() read and write a JSON file in one call through the PHP streams layer (open_basedir and stream wrappers apply). fastjson_file_encode() opens the destination in write mode, so it is a convenience helper, not an atomic config/state-file update primitive; use your own temp-file + rename flow when partial writes would be unsafe. File I/O failures reuse FASTJSON_ERROR_SYNTAX to stay compatible with the JSON_ERROR_* code range, so callers that need to separate filesystem faults from parse or encode failures should check fastjson_last_error_msg() for the Failed to ... file messages. fastjson_pointer_get() extracts a single value by RFC 6901 JSON Pointer without materializing the rest of the document; fastjson_pointer_exists() reports whether a pointer resolves (distinguishing "present but null" from "absent"); fastjson_pointer_set() sets a single value by pointer and returns the re-serialized document, splicing the edit directly into the parsed document so a single edit on a large document skips a full decode/re-encode; fastjson_merge_patch() applies an RFC 7386 merge patch.

Error location: beyond fastjson_last_error() / _msg(), fastjson_last_error_pos() returns the byte offset of the most recent parse error (-1 when none), and fastjson_last_error_info() bundles ['code', 'msg', 'pos', 'line', 'col'] (1-based line/column) in one call, useful when a caller, or an agent, needs to point at exactly where malformed JSON broke.

See CHANGELOG.md for the full feature list and the divergences from ext/json that fastjson does not aim to mirror byte-for-byte.

📊 Performance

Throughput vs ext/json on the full 14.8 MB / 15-file canonical corpus from simdjson_php's jsonexamples. i9-13950HX, release build of both PHP and fastjson (-O2, Debug Build => no):

Operation fastjson ext/json speedup
Decode (stdClass) 602 MB/s 227 MB/s 2.66x
Decode (assoc array) 628 MB/s 237 MB/s 2.65x
Encode 1,092 MB/s 180 MB/s 6.06x
Validate 1,352 MB/s 265 MB/s 5.10x

A visual side-by-side against ext/json on PHP 8.4 is published at iliaal.github.io/fastjson. Methodology, per-file numbers, small-corpus + per-call latency breakdown, and how to reproduce: bench/README.md and bench/baseline.md.

Memory tradeoff

fastjson trades memory for speed on decode (yyjson's two-stage parser holds the doc alongside the zval tree). Decode peak is ~1.7x ext/json's heap. Encode runs one-stage (direct-write into smart_str using yyjson primitives) so encode memory is at near-parity with ext/json (~1.1x). Validate peaks at ~101x: lower than ext/json's true streaming validator (constant ~80 bytes) but already 2.7x better than yyjson's stock read path thanks to vendor patch P-002. See vendor/yyjson/PATCHES.md. For most callers the speedup is worth the memory headroom; if you're validate-heavy on giant inputs in tight memory_limit settings, it's a real consideration.

✨ What's in the box

  • Bundled yyjson 0.12.0 (MIT) with three local patches (P-001, P-002, P-003). Full notes in vendor/yyjson/PATCHES.md.
  • yyjson allocator routes every malloc/realloc/free through Zend's emalloc/erealloc/efree. JSON allocations participate in memory_limit accounting and request-scoped cleanup.
  • FASTJSON_ERROR_* constants intentionally match JSON_ERROR_* byte-for-byte, so callers can use either set.
  • 62-test compat harness rewritten from php-src/ext/json/tests/*.phpt runs alongside the native phpt suite. tests/upstream-json/.skiplist and tests/upstream-json/STATE.md track which upstream tests fastjson does not aim to pass byte-for-byte.
  • Depth and stack-overflow guards on encode and decode via zend_call_stack_overflowed. Deeply chained inputs fail cleanly instead of being killed by the OS.

Roadmap

  • fastjson_validate success-path depth enforcement (currently argument-validated but the cap is not walked, since yyjson's validate-only mode has no parse-time depth flag and a post-parse walk halves the success-path throughput)
  • Streaming / incremental decode and encode

🔗 Native PHP extensions

Companion native PHP extensions:

  • php_excel: native Excel I/O via LibXL. 7-10× faster than PhpSpreadsheet, full XLS/XLSX with formulas, formatting, and styling.
  • mdparser: native CommonMark + GFM markdown parser via md4c. 15-30× faster than pure-PHP libraries.
  • php_clickhouse: native ClickHouse client speaking the wire protocol directly. Picks up where SeasClick left off.
  • pdo_duckdb: PDO driver for DuckDB, analytical SQL in your PHP stack.
  • phpser: decoder-optimized binary serializer for cache workloads. Faster than igbinary on packed numerics and DTO batches.
  • fast_uuid: high-throughput UUID generation (v1/v4/v7), batched CSPRNG and SIMD hex formatter, ramsey-compatible API.
  • fastchart: native chart-rendering extension. 38 chart types behind one fluent OO API, SVG-canonical with PNG/JPG/WebP and optional PDF output.
  • statgrab: system statistics (CPU, memory, disk, network) via libstatgrab, no parsing /proc by hand.
  • phonetic: native phonetic name matching (Double Metaphone, Beider-Morse, Daitch-Mokotoff, NYSIIS, Match Rating), the encoders PHP core lacks.

License

  • Wrapper code (fastjson*.c, php_fastjson.h) under BSD 3-Clause.
  • Bundled yyjson sources under MIT. Upstream LICENSE preserved verbatim and surfaced in Section 2 of the project LICENSE file.

Follow @iliaa on XBlog • If this sped up your stack, ⭐ star it!

iliaal/fastjson 适用场景与选型建议

iliaal/fastjson 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25 次下载、GitHub Stars 达 19, 最近一次更新时间为 2026 年 05 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 iliaal/fastjson 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 25
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 20
  • 点击次数: 42
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 19
  • Watchers: 3
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2026-05-11