There are two ways to achieve this, it depends on what you prefer and whether your action should support multiple _format types.
Option A is an action that returns JSON
You can completely bypass the template.
In your controller, remove the @Template annotation and instead return new Response(json_encode($process_data));
Option B is an action that supports different formats, or you just want to display JSON in the template
As a result of an action that displays different formats, I refer to an action with this route:
@Route("/check/{key}.{_format}", defaults={"_format"="json"} @Template
Although the controller in this matter follows the path of "an action that only supports JSON, but you want to display it in the template."
Assuming the controller processAction returns a return array('data' => $process_data); , since the question asks how to do this, since the JSON inside the template named process.json.twig should run as follows {{ data|json_encode }} , there is no need to pre-process the data or turn it into another array or something similar inside the template .
source share