Pretty-printing JSON with custom indentation

PHP 5.4 added the JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE constants for use with the json_encode() function.

For example, you can use the JSON_PRETTY_PRINT constant to encode a value to a JSON string with four spaces of indentation.

<?php

declare(strict_types=1);

$data = [
    'name' => 'Andreas Möller',
    'emoji' => '🤓',
    'urls' => [
        'https://localheinz.com',
        'https://github.com/localheinz',
        'https://twitter.com/localheinz',
    ],
];

echo json_encode(
    $data,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
{
    "name":"Andreas Möller",
    "emoji":"🤓",
    "urls":[
        "https://localheinz.com",
        "https://github.com/localheinz",
        "https://twitter.com/localheinz"
    ]
}

But what if you need to indent a JSON string with two spaces or tabs?

In June 2022, only 7 out of 21 people voted for a related json_encode indentation RFC, which proposed adding a parameter to the json_encode() that would allow configuring the number of spaces to use for indenting the resulting JSON string.

If you need to indent a JSON string with an indentation other than four spaces, you need to solve the problem in PHP code.

But fear not - based on source code I found in composer/composer, linking back to an article by Dave Perrett from 2008, I have built the PHP package ergebnis/json-printer.

To install the PHP package, run

composer require ergebnis/json-printer

After adjusting the example from earlier using the printer, the script produces a JSON string indented with two spaces.

<?php

declare(strict_types=1);

use Ergebnis\Json\Printer;

$data = [
    'name' => 'Andreas Möller',
    'emoji' => '🤓',
    'urls' => [
        'https://localheinz.com',
        'https://github.com/localheinz',
        'https://twitter.com/localheinz',
    ],
];

$json = json_encode(
    $data,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);

$printer = new Printer\Printer();

echo $printer->print(
    $json,
    str_repeat(' ', 2)
);
{
  "name":"Andreas Möller",
  "emoji":"🤓",
  "urls":[
    "https://localheinz.com",
    "https://github.com/localheinz",
    "https://twitter.com/localheinz"
  ]
}

I hope it helps - I definitely need this for normalizing composer.json!

Project on GitHub

ergebnis/json-printer

Integrate WorkflowCode CoverageType CoverageLatest Stable VersionTotal DownloadsMonthly Downloads

📃 Provides a composer package with a JSON printer, allowing for flexible indentation.

Find out more at ergebnis/json-printer.

Do you find this article helpful?

Do you need help with your PHP project?