Skip to content

Instantly share code, notes, and snippets.

@signalpoint
Created July 23, 2015 21:52
Show Gist options
  • Save signalpoint/97bfd628f47a5ddaeb05 to your computer and use it in GitHub Desktop.
Save signalpoint/97bfd628f47a5ddaeb05 to your computer and use it in GitHub Desktop.
Drupal 8 Output JSON
<?php
// ...
use Symfony\Component\HttpFoundation\Response;
// Then later on (inside your controller's class), you have a function used
// for the route_name (on a hook_menu() item in your .module file), this
// function can return a JSON response...
$response = new Response();
$response->setContent(json_encode(array('hello' => 'world', 'goodbye' => 'world')));
$response->headers->set('Content-Type', 'application/json');
return $response;
@niccottrell
Copy link

I believe you can now do:

return new JsonResponse($array, 200, ['Content-Type'=> 'application/json']);

or just

return new JsonResponse($array);

@fisherman90
Copy link

@niccottrell would be a nice shortcut, but I tried it and it unfortunately didn't work for me in Drupal 8.1.7 :(
I had to use the Gist code above and it works like a charm :)
Thanks for the help! 👍

@cleverex-ali
Copy link

Thanks a lot sir.

@fkaizo
Copy link

fkaizo commented Jul 27, 2018

For JsonResponse you have to declare it before.
use Symfony\Component\HttpFoundation\JsonResponse;

https://api.symfony.com/4.0/Symfony/Component/HttpFoundation/JsonResponse.html

@greggles
Copy link

For anyone arriving here from Google: JsonResponse works well these days. Might not have back in 2016.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment