PHPackages                             rhinox/fractured-json - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. rhinox/fractured-json

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

rhinox/fractured-json
=====================

JSON formatter that produces highly readable but fairly compact output

v1.0.0(4mo ago)11MITPHPPHP &gt;=8.4

Since Jan 4Pushed 4mo agoCompare

[ Source](https://github.com/rhinox-php/fractured-json)[ Packagist](https://packagist.org/packages/rhinox/fractured-json)[ RSS](/packages/rhinox-fractured-json/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

FracturedJson for PHP
=====================

[](#fracturedjson-for-php)

A JSON formatter that produces human-readable output with intelligent line breaks and table-like alignment. It strikes a balance between compact and expanded formats, making large JSON documents much easier to read.

This is a PHP port of [FracturedJsonJs](https://github.com/j-brooke/FracturedJson), maintaining full compatibility with the original TypeScript implementation.

Features
--------

[](#features)

- **Smart formatting**: Automatically chooses between inline, compact multiline, table, and expanded formats based on content
- **Table alignment**: Arrays of similar objects are formatted as aligned tables
- **Number alignment**: Numbers in columns can be aligned by decimal point
- **Comment preservation**: Supports JSONC (JSON with comments)
- **Configurable**: Extensive options to customize output format
- **CLI tool**: Command-line interface for formatting files or piped input

Requirements
------------

[](#requirements)

- PHP 8.4 or higher
- mbstring extension

Installation
------------

[](#installation)

```
composer require rhinox/fractured-json
```

Quick Start
-----------

[](#quick-start)

### Library Usage

[](#library-usage)

```
use Rhinox\FracturedJson\Formatting\Formatter;

$formatter = new Formatter();
$json = '{"name":"Alice","scores":[95,87,92],"active":true}';

echo $formatter->reformat($json);
```

Output:

```
{ "name": "Alice", "scores": [95, 87, 92], "active": true }
```

### CLI Usage

[](#cli-usage)

```
# Format a file
vendor/bin/fractured-json data.json

# Format from stdin
echo '{"a":1,"b":2}' | vendor/bin/fractured-json

# Format in place
vendor/bin/fractured-json -i config.json
```

Formatting Examples
-------------------

[](#formatting-examples)

FracturedJson automatically selects the best format based on the data structure and configured options.

### Inline Format

[](#inline-format)

Simple, short content stays on one line:

```
{ "name": "Alice", "age": 30, "active": true }
```

### Table Format

[](#table-format)

Arrays of similar objects are aligned as tables:

```
[
    { "name": "Alice",   "age": 30, "city": "New York" },
    { "name": "Bob",     "age": 25, "city": "Boston"   },
    { "name": "Charlie", "age": 35, "city": "Chicago"  }
]
```

### Compact Multiline Format

[](#compact-multiline-format)

Long arrays of simple values are wrapped across multiple lines:

```
{
    "primes": [
          2,   3,   5,   7,  11,  13,  17,  19,  23,  29,  31,  37,  41,  43,  47,
         53,  59,  61,  67,  71,  73,  79,  83,  89,  97, 101, 103, 107, 109, 113
    ]
}
```

### Expanded Format

[](#expanded-format)

Complex nested structures are fully expanded:

```
{
    "users": [
        {
            "name": "Alice",
            "address": {
                "street": "123 Main St",
                "city": "New York"
            }
        }
    ]
}
```

Configuration
-------------

[](#configuration)

### Using Options

[](#using-options)

```
use Rhinox\FracturedJson\Formatting\Formatter;
use Rhinox\FracturedJson\Formatting\FracturedJsonOptions;
use Rhinox\FracturedJson\Enums\CommentPolicy;

$options = new FracturedJsonOptions();
$options->maxTotalLineLength = 80;
$options->indentSpaces = 2;
$options->commentPolicy = CommentPolicy::Preserve;

$formatter = new Formatter($options);
echo $formatter->reformat($json);
```

### Available Options

[](#available-options)

OptionTypeDefaultDescription`jsonEolStyle`EolStyle`Lf`Line ending style (`Lf` or `Crlf`)`maxTotalLineLength`int`120`Maximum line length before wrapping`maxInlineComplexity`int`2`Max nesting depth for inline formatting`maxCompactArrayComplexity`int`2`Max nesting for compact multiline arrays`maxTableRowComplexity`int`2`Max nesting for table row formatting`indentSpaces`int`4`Spaces per indentation level`useTabToIndent`bool`false`Use tabs instead of spaces`nestedBracketPadding`bool`true`Spaces inside brackets for nested content`simpleBracketPadding`bool`false`Spaces inside brackets for simple content`colonPadding`bool`true`Space after colons`commaPadding`bool`true`Space after commas`commentPolicy`CommentPolicy`TreatAsError`How to handle comments`preserveBlankLines`bool`false`Keep blank lines from input`allowTrailingCommas`bool`false`Allow trailing commas in input`numberListAlignment`NumberListAlignment`Decimal`Number alignment in columns`alwaysExpandDepth`int`-1`Depth at which to always expand### Comment Policy

[](#comment-policy)

```
use Rhinox\FracturedJson\Enums\CommentPolicy;

// Throw exception if comments found (default)
$options->commentPolicy = CommentPolicy::TreatAsError;

// Remove comments from output
$options->commentPolicy = CommentPolicy::Remove;

// Preserve comments in output
$options->commentPolicy = CommentPolicy::Preserve;
```

### Number Alignment

[](#number-alignment)

```
use Rhinox\FracturedJson\Enums\NumberListAlignment;

// Left align numbers
$options->numberListAlignment = NumberListAlignment::Left;

// Right align numbers
$options->numberListAlignment = NumberListAlignment::Right;

// Align on decimal point (default)
$options->numberListAlignment = NumberListAlignment::Decimal;

// Normalize precision and align
$options->numberListAlignment = NumberListAlignment::Normalize;
```

API Reference
-------------

[](#api-reference)

### Formatter Class

[](#formatter-class)

#### `reformat(string $jsonText, int $startingDepth = 0): string`

[](#reformatstring-jsontext-int-startingdepth--0-string)

Reads JSON text and returns a formatted string.

```
$formatter = new Formatter();
$output = $formatter->reformat('{"a":1,"b":2}');
```

#### `serialize(mixed $element, int $startingDepth = 0, int $recursionLimit = 100): ?string`

[](#serializemixed-element-int-startingdepth--0-int-recursionlimit--100-string)

Serializes a PHP value to formatted JSON.

```
$formatter = new Formatter();
$output = $formatter->serialize(['name' => 'Alice', 'age' => 30]);
```

#### `minify(string $jsonText): string`

[](#minifystring-jsontext-string)

Returns minified JSON with all unnecessary whitespace removed.

```
$formatter = new Formatter();
$output = $formatter->minify('{ "a": 1, "b": 2 }');
// Output: {"a":1,"b":2}
```

### Custom String Length Function

[](#custom-string-length-function)

For special alignment needs (e.g., East Asian character width), you can provide a custom string length function:

```
$formatter = new Formatter();
$formatter->stringLengthFunc = fn(string $s) => mb_strwidth($s, 'UTF-8');
```

CLI Reference
-------------

[](#cli-reference)

```
Usage:
  fractured-json [options] [files...]
  cat file.json | fractured-json [options]

Options:
  -h, --help                 Show help message
  -v, --version              Show version
  -i, --in-place             Modify files in place
  -m, --minify               Minify instead of format
  -c, --comments             Preserve comments (JSONC)

Formatting Options:
  --indent                Spaces per indent level (default: 4)
  --tabs                     Use tabs for indentation
  --max-line-length       Maximum line length (default: 120)
  --max-inline-complexity  Max nesting for inline arrays/objects
  --expand-depth          Depth at which to always expand
  --crlf                     Use CRLF line endings
  --no-bracket-padding       No spaces inside brackets
  --simple-bracket-padding   Add spaces inside simple brackets
  --number-align       left, right, decimal, or normalize
  --preserve-blank-lines     Keep blank lines from input
  --trailing-commas          Allow trailing commas in input

```

### CLI Examples

[](#cli-examples)

```
# Format and print to stdout
vendor/bin/fractured-json data.json

# Format multiple files in place
vendor/bin/fractured-json -i *.json

# Format with 2-space indents and 80 char lines
vendor/bin/fractured-json --indent 2 --max-line-length 80 data.json

# Format JSONC file preserving comments
vendor/bin/fractured-json -c config.jsonc

# Minify
vendor/bin/fractured-json -m large-file.json

# Pipe from another command
curl -s https://api.example.com/data | vendor/bin/fractured-json
```

Error Handling
--------------

[](#error-handling)

The formatter throws `FracturedJsonException` for invalid input:

```
use Rhinox\FracturedJson\Formatting\Formatter;
use Rhinox\FracturedJson\Exceptions\FracturedJsonException;

$formatter = new Formatter();

try {
    $output = $formatter->reformat('invalid json');
} catch (FracturedJsonException $e) {
    echo "Error: " . $e->getMessage();
}
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Credits
-------

[](#credits)

This is a PHP port of [FracturedJson](https://github.com/j-brooke/FracturedJson) by J-Brooke.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance77

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

126d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0befeec6d305b366fc58426c96cb7a86242d65ef632a33b7dc6aa60a24d434e9?d=identicon)[Petah](/maintainers/Petah)

---

Top Contributors

[![Petah](https://avatars.githubusercontent.com/u/134799?v=4)](https://github.com/Petah "Petah (2 commits)")

---

Tags

jsonformatterstringifycommentsbeautifierjsonccompactpretty printer

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rhinox-fractured-json/health.svg)

```
[![Health](https://phpackages.com/badges/rhinox-fractured-json/health.svg)](https://phpackages.com/packages/rhinox-fractured-json)
```

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[ergebnis/json-printer

Provides a JSON printer, allowing for flexible indentation.

9138.2M24](/packages/ergebnis-json-printer)[colinodell/json5

UTF-8 compatible JSON5 parser for PHP

30422.2M45](/packages/colinodell-json5)[ergebnis/json-normalizer

Provides generic and vendor-specific normalizers for normalizing JSON documents.

8237.5M6](/packages/ergebnis-json-normalizer)[laktak/hjson

JSON for Humans. A configuration file format with relaxed syntax, fewer mistakes and more comments.

86233.7k12](/packages/laktak-hjson)[dragon-code/codestyler

A tool to automatically fix Coding Style Standards issues by The Dragon Code.

291.8M16](/packages/dragon-code-codestyler)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
