Editable JSON AST with visitor traversal and formatting-preserving printing.
JsonRecast is a PHP library for tools that need to read, edit, and rewrite JSON without causing noisy diffs. It parses JSON into an editable AST, lets visitors mutate or replace nodes, tracks the changed parts, then prints the document back with the original spacing and newline style where possible. Its traversal model is inspired by nikic/PHP-Parser, adapted for JSON documents.
Contents
How It Works
JsonRecast::parse()runs theLexerandJsonParserto build aJsonDocument, an editable AST.JsonRecast::traverse()walks the document with yourNodeJsonVisitorand returns aJsonRecastResultwhoseNodeChangeSettracks the changed nodes. This step is optional — you can also edit the AST directly.JsonRecast::print()accepts either result and uses theJsonPreservingPrinterto write the JSON back with the original formatting preserved where possible.
Why Use JsonRecast
- Build config migration tools that preserve a user’s formatting choices.
- Traverse JSON as an AST instead of nested arrays.
- Use path-aware visitors for focused edits.
- Keep number spellings such as
1,1.0, and1e0. - Dump ASTs while writing visitors or debugging transformations.
Where To Go Next
- Quick Start covers installation, parsing, traversal, and printing.
- Editing And Printing shows object, array, and scalar edits that preserve formatting.
- Traversal And Paths explains visitor hooks, change tracking, and
NodeJsonPath. - Node Reference lists the node classes and helper methods.
- Parsing And Printers covers parse errors, preserving output, and pretty output.
- Advanced Tricks covers practical patterns for project tooling and low-noise migrations.
- AST Dumper shows how to inspect parsed or transformed documents.