Pretty-Printing JSON with PHP

Pretty-Printing JSON with PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Pretty-Printing JSON with PHP

When you output a large associative array using json_encode, the default behavior produces a single-line string. This is efficient for parsing, but it makes debugging difficult and reduces readability when inspecting the response in a browser or API client. You might have seen examples of formatted output similar to what Facebook used to provide, where keys are indented and values sit on new lines. Achieving this in PHP doesn't require external libraries or complex hacks; it relies entirely on an option built into the standard json_encode function.

The core mechanism is the JSON_PRETTY_PRINT flag. By passing this constant as the second argument to your encoding function, you instruct the engine to add whitespace characters for formatting. Here is how the example script changes:

$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');

// Use JSON_PRETTY_PRINT for formatted output
echo json_encode($data, JSON_PRETTY_PRINT);

This single line of code transforms the compact output into a multi-line structure with standard indentation. The default indentation level is 4 spaces, but this can be customized via the third argument if you need stricter control over spacing.

Controlling Indentation Levels

While the default 4-space indent is standard for many tools, you might prefer tabs or a different number of spaces per level. The json_encode function accepts a third parameter specifically for this purpose. You can pass either an integer representing spaces or a string containing tab characters ("\t").

For instance, if you want to switch from 4 spaces to 2 spaces per indentation level, the code looks like this:

echo json_encode($data, JSON_PRETTY_PRINT, 2);

Alternatively, using tabs is straightforward:

echo json_encode($data, JSON_PRETTY_PRINT, "\t");

This flexibility allows you to match the formatting style required by your specific frontend framework or API documentation without writing custom string manipulation logic.

Handling Objects vs. Arrays

It is important to note that JSON_PRETTY_PRINT works regardless of whether the top-level structure is an associative array or an object represented as an array of key-value pairs. However, if you are encoding a complex nested structure containing both arrays and objects, the function will format every level recursively.

Consider a scenario where you have a user profile with nested metadata:

$user = array(
    'id' => 101,
    'name' => 'Alice',
    'preferences' => array(
        'theme' => 'dark',
        'notifications' => true
    )
);

echo json_encode($user, JSON_PRETTY_PRINT, 2);

The output will maintain the hierarchy cleanly. This is particularly useful when debugging complex payloads where the depth of nesting makes single-line output impossible to parse visually.

Performance Considerations

While JSON_PRETTY_PRINT is convenient, it does introduce a slight overhead in terms of output size and CPU cycles spent on string formatting. In high-performance API scenarios where data is sent to a client that will immediately parse and discard the whitespace, this extra data transfer can be negligible or slightly detrimental depending on bandwidth constraints.

If you are building a script that feeds JSON to another system via a pipe or an internal service mesh, you should stick to the compact format. Use JSON_PRETTY_PRINT primarily when the output is destined for human consumption, such as debugging endpoints, logging errors directly to the console, or serving raw responses where readability is the priority.

The JSON_UNESCAPED_UNICODE Flag

Another common requirement alongside pretty-printing is handling UTF-8 characters correctly. By default, json_encode escapes Unicode characters (e.g., converting "é" to "\u00e9"). If you want to preserve the original characters in your formatted output, you should combine JSON_PRETTY_PRINT with JSON_UNESCAPED_UNICODE.

echo json_encode($data, JSON_PRETTY_PRINT, 2, JSON_UNESCAPED_UNICODE);

This combination ensures that your pretty-printed JSON is both readable and correctly renders non-ASCII characters without double-encoding them. This is a crucial trade-off when dealing with internationalized content, as it prevents the need for front-end developers to write complex decoding logic just to display simple text in a formatted response.

Our network