How to return a JSON response from a controller in Magento 2

- Fire development, Magento 2

Magento 2 Development

Below, we describe how to return a JSON response from a controller in Magento 2.

'

Dmitry Fedyuk provides the following example of Magento 2 backend controller with JSON response:

etc/adminhtml/routes.xml:

And these are examples from the Magento 2 core:

magento/magento2/blob/8fd3e8/app/code/Magento/Backend/Controller/Adminhtml/Ajax/Translate.php#L38-L58

 magento/magento2/blob/8fd3e8/app/code/Magento/Catalog/Controller/Adminhtml/Category/CategoriesJson.php#L36-L41

agento/magento2/blob/8fd3e8/app/code/Magento/Catalog/Controller/Adminhtml/Category/CategoriesJson.php#L48-L64

magento/magento2/blob/8fd3e8/app/code/Magento/Customer/Controller/Ajax/Login.php#L135-L143

magento/magento2/blob/8fd3e8/app/code/Magento/Customer/Controller/Ajax/Login.php#L159-L162

magento/magento2/blob/8fd3e8/app/code/Magento/Customer/Controller/Ajax/Login.php#L191-L193

Source

More tips from the cookbook

'