How to send the JSON data from a Drupal 8 site?

Send the JSON data with Controller

However, redefining an array through normalizers can be too inconvenient if you need to get the absolutely custom JSON array from a specific path. In addition, an override of the normalizer will affect the JSON structure of all the nodes of this content type, that’s why you can use a simpler method: you can always send the JSON data using the controller having adjusted this data to a certain path. And this method can really help to solve a more specific problem, for example, in my case, it was necessary to place all the nodes in the common array, which is very difficult or even impossible to achieve through a view. You can learn how to create a custom module with a controller in this article.

First, create a routing file and assign a path which will use the GET method to get JSON.

The controller file will look like in the code sample below. Using the custom method in the controller and JSONResponse, we can send the JSON array exactly as we want it to.

Here we do not use hardcoded Symfony and the Rest module methods in order to change the JSON array but create our own.

Facebook Comments
Spread the love

Posted by News Monkey