Editable JSON AST with visitor traversal and formatting-preserving printing.

Latest Version ci build Code Coverage PHPStan Downloads

Windows macOS Linux

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

  1. How It Works
  2. Why Use JsonRecast
  3. Where To Go Next

How It Works

JsonRecast flow: parse JSON into a JsonDocument, optionally traverse it with visitors, then print with the original formatting preserved

  • JsonRecast::parse() runs the Lexer and JsonParser to build a JsonDocument, an editable AST.
  • JsonRecast::traverse() walks the document with your NodeJsonVisitor and returns a JsonRecastResult whose NodeChangeSet tracks the changed nodes. This step is optional — you can also edit the AST directly.
  • JsonRecast::print() accepts either result and uses the JsonPreservingPrinter to 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, and 1e0.
  • Dump ASTs while writing visitors or debugging transformations.

Where To Go Next