Export Menus as JSON

Public

This snippet showcases the ease of broadcasting custom JSON data in Drupal. Basically, the idea is to pass an associative array and convert it to "drupal_json_output" using the "delivery_callback" menu property. In the example below, the exported menus' JSON data will be accessible in this URL: http://www.example.com/menus/json.

Get raw version
php
  1. /**
  2.  * Implements hook_menu().
  3.  */
  4. function my_module_menu() {
  5. $items = array();
  6.  
  7. $items['menus/json'] = array(
  8. 'page callback' => '_retrieve_menus',
  9. 'access callback' => TRUE,
  10. 'delivery callback' => 'drupal_json_output',
  11. );
  12.  
  13. return $items;
  14. }
  15.  
  16. function _retrieve_menus() {
  17. $query_string = "SELECT link_title, link_path FROM menu_links WHERE menu_name = 'main-menu'";
  18. $result = db_query($query_string);
  19.  
  20. if ($result) {
  21. while ($menu = $result->fetchAssoc()) {
  22. $menus[] = $menu;
  23. }
  24. }
  25.  
  26. return array('data' => $menus);
  27. }