Rendering JSON with JsonView in Extbase
\TYPO3\ renders the variables an action
assigns as JSON instead of passing them to
a Fluid template. The action keeps the usual pattern: it assigns variables to
the view and returns a response, and the view decides what the output looks
like.
This page shows how an action switches to
Json, which variables end up in
the output, and how to shape the data. Where the JSON is delivered is a
separate question, see
Beyond HTML delivery.
On this page
Switching an Extbase action to JsonView
Extbase creates the view of an action itself. The protected property
$default of
Action decides which
view that is: Fluid when it is
null
, the default, or
Json when it is set to
Json.
Setting the property in an initializeXxxAction() method switches one action and leaves the others of the controller with Fluid. Extbase calls this method before it creates the view:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Controller;
use MyVendor\MyExtension\Domain\Repository\ConferenceRepository;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\View\JsonView;
class ConferenceController extends ActionController
{
public function __construct(
protected readonly ConferenceRepository $conferenceRepository,
) {}
protected function initializeUpcomingAction(): void
{
$this->defaultViewObjectName = JsonView::class;
}
public function upcomingAction(): ResponseInterface
{
$conferences = [];
foreach ($this->conferenceRepository->findUpcoming() as $conference) {
$conferences[] = [
'uid' => $conference->getUid(),
'title' => $conference->getTitle(),
'conferenceDate' => $conference->getConferenceDate(),
];
}
$this->view->assignMultiple([
'conferences' => $conferences,
'total' => count($conferences),
]);
$this->view->setVariablesToRender(['conferences', 'total']);
return $this->jsonResponse();
}
}
The action then assigns its variables, names the ones to render with
set, and returns
$this->json, which
renders the view and sets the content type application/:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Controller;
use MyVendor\MyExtension\Domain\Repository\ConferenceRepository;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\View\JsonView;
class ConferenceController extends ActionController
{
public function __construct(
protected readonly ConferenceRepository $conferenceRepository,
) {}
protected function initializeUpcomingAction(): void
{
$this->defaultViewObjectName = JsonView::class;
}
public function upcomingAction(): ResponseInterface
{
$conferences = [];
foreach ($this->conferenceRepository->findUpcoming() as $conference) {
$conferences[] = [
'uid' => $conference->getUid(),
'title' => $conference->getTitle(),
'conferenceDate' => $conference->getConferenceDate(),
];
}
$this->view->assignMultiple([
'conferences' => $conferences,
'total' => count($conferences),
]);
$this->view->setVariablesToRender(['conferences', 'total']);
return $this->jsonResponse();
}
}
A controller whose actions all answer with JSON sets the property once in its constructor instead, as the backend controllers of the extension manager in the TYPO3 Core do.
Json is the only view class
besides Fluid that Extbase accepts in
$default. Any other
class name raises an exception. An action that needs a different view creates
it itself, for example with the
view factory, and passes the rendered
string to the response.
Choosing the variables JsonView renders
Json renders only the variables
named in
set. Everything else assigned to the view,
including the
settings
that Extbase assigns to every view, stays out of
the output. Without a call to
set, the view renders
a variable called value and nothing else, so an action that forgets the call
returns null.
The number of variables decides the shape of the JSON:
-
Several variables are rendered as a JSON object with one member per variable. The action above returns:
Response of upcomingAction(){ "conferences": [ { "uid": 12, "title": "Developer Days", "conferenceDate": "2027-03-18T09:00:00+01:00" } ], "total": 1 }Copied! - A single variable is rendered as its value alone, without a key. With
set, the same action would return the bare JSON array of conferences.Variables To Render ( ['conferences'])
A PHP list becomes a JSON array, and an array with string keys becomes a JSON object.
Shaping the JSON output of an Extbase action in PHP
Json converts what it receives as
follows:
- Arrays are converted element by element.
- Dates, that is objects implementing DateTimeInterface, become strings in the ISO 8601 format with time zone offset, as shown above.
- Other objects, such as domain models, become JSON objects with one member per readable property: each public property, and each property that has a public getter. Only properties holding a scalar value are included. A property that holds an object or an array, such as a relation to another model, is left out without an error.
Assigning domain models directly is therefore rarely what an endpoint needs.
Every readable property becomes public, including fields such as
pid
that the client has no use for and fields the model only keeps for internal
purposes. At the same time the relations are missing.
Build the data the client needs in the action instead, as an array or as a data transfer object (DTO) with exactly the fields to publish, the way the example above does. The output then shows at one glance what the endpoint exposes, a new property on the model does not appear in the JSON unnoticed, and related data is included by reading it explicitly, for example the name of a conference's location.
Returning JSON from an Extbase action without JsonView
When the action builds an array anyway, encoding it directly is just as short.
$this->json accepts the JSON string and uses it as the body,
so no view configuration is needed:
public function countAction(): ResponseInterface
{
return $this->jsonResponse(json_encode(
['count' => $this->conferenceRepository->countAll()],
JSON_THROW_ON_ERROR,
));
}
Extbase still prepares the default view for such an action, but it is never
rendered.
Json is the better fit
when the action should stay with the usual assign-and-render pattern, and when
the output contains dates that should be formatted consistently.
Delivering the JSON of an Extbase action at its own URL
$this->json sets the content type of the action's response.
For a plugin rendered on a regular page, Extbase does not replace the page with
that response: the JSON is inserted into the page HTML, and its content type
becomes the content type of the whole page, see the pitfall
An action returning JSON breaks the page.
The JSON therefore needs a URL of its own, for example a typeNum page type that renders only the plugin. Loading Extbase data with fetch() shows the complete path from the action to a script that displays the data, and Ways to deliver non-HTML output from TYPO3 compares the other options.
In a headless setup, the JSON of the action becomes part of the JSON of the page that contains the plugin, see Letting an Extbase plugin answer with JsonView.