Drupal - How can I return actual JSON using Drupal?

For Drupal 6, you can use drupal_json

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json($result);
    exit;
}

For Drupal 7, change it to use drupal_json_output

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json_output($result);
    drupal_exit();
}

It would also probably be safer to parse out the query to sanitize, error check, etc, instead of just trying to return the result.


I saw that there was no answer provided for Drupal 8.

In order to process JSON in Drupal 8, use the following code:

  <?php
     use Symfony\Component\HttpFoundation\JsonResponse;
     // ...
     $options = _menu_get_options(menu_get_menus(), $available_menus, array('mlid' => 0));
     return new JsonResponse($options);
  ?>

You can read more about it here