Pretty Print JSON Response in Symfony 7

Pretty Print JSON Response in Symfony 7

Symfony framework provides the JsonResponse class that allows to represent an HTTP response in JSON format. This class returns a JSON response that is not formatted and can be hard to read when debugging the application during development.

This tutorial provides example how to pretty print JSON response in Symfony 7 application.

The JsonResponse class has the encodingOptions property which specifies default JSON encoding options. We can extend this class and override encodingOptions property.

src/Component/Response/PrettyJsonResponse.php

<?php

namespace App\Component\Response;

use Symfony\Component\HttpFoundation\JsonResponse;

class PrettyJsonResponse extends JsonResponse
{
    protected int $encodingOptions = self::DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT;
}

Now a new class can be used in controller as follows:

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Component\Response\PrettyJsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(): Response
    {
        return new PrettyJsonResponse(
            [
                'name' => 'John',
                'age' => 25,
            ]
        );
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.