Learn how to send a pretty-printed version of the JsonResponse class in Symfony 4.

How to pretty print a JsonResponse in Symfony 4

Constantly we are looking for a way to do complicated stuff so easy as possible in our projects, this means constant programming and debugging basic things as plain responses of our website. In case that you are working with your own API or just a basic response in your controller that returns a JSON String as response, you may know that the responses using the JsonResponse class of Symfony 4 returns a minified version of the string, just as the json_encode method does by default, for example:

<?php

// src/Controller/PagesController.php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use Symfony\Component\HttpFoundation\JsonResponse;

class PagesController extends AbstractController
{
    /**
     * @Route("/", name="app_index")
     */
    public function index()
    {
        return new JsonResponse([
            'name' => "Carlos",
            'age' => 22,
            'location' => [
                'city' => 'Bucaramanga',
                'state' => 'Santander',
                'country' => 'Colombia'
            ]
        ]);
    }
}

This will return as response in the browser the following string:

{"name":"Carlos","age":22,"location":{"city":"Bucaramanga","state":"Santander","country":"Colombia"}}

As you can see, even this single object it's hard to read, so imagine how a huge object would look like ! Of course you can debug previously the objects that you want to return using the dump method in your controller, however if you want to do it through the old school way, it would be great to send a pretty printed version of the response to see it in the browser. This can be easily done and i'll explain you shortly how to do it.

Pretty print response modifying the response

The JsonResponse class has the setEncodingOptions method, a method that sets options used while encoding data to JSON. By default, the class uses the following options to encode the JSON response (with the json_encode method):

// Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML.
// 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
const DEFAULT_ENCODING_OPTIONS = 15;

You can then concatenate the new JSON_PRETTY_PRINT option like this in the response:

$response = new JsonResponse([ // data ]);

$response->setEncodingOptions( $response->getEncodingOptions() | JSON_PRETTY_PRINT );

return $response;

The following example shows how to do it in a controller:

<?php

// src/Controller/PagesController.php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use Symfony\Component\HttpFoundation\JsonResponse;

class PagesController extends AbstractController
{
    /**
     * @Route("/", name="app_index")
     */
    public function index()
    {
        $response = new JsonResponse([
            'name' => "Carlos",
            'age' => 22,
            'location' => [
                'city' => 'Bucaramanga',
                'state' => 'Santander',
                'country' => 'Colombia'
            ]
        ]);
        
        // Use the JSON_PRETTY_PRINT 
        $response->setEncodingOptions( $response->getEncodingOptions() | JSON_PRETTY_PRINT );
        
        return $response;
    }
}

And it will return the following string as response in the browser:

{
    "name": "Carlos",
    "age": 22,
    "location": {
        "city": "Bucaramanga",
        "state": "Santander",
        "country": "Colombia"
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors