JSON output in Drupal 7

I need to expose some nodes in Drupal 7 as JSON for downstream consumers. I spend about 45 minutes Googleing for a Drupal 7 module with functionality like “views datasource” in Drupal 6 – found nothing – wrote this instead:  (created mytheme/page–json.tpl.php)

<?php
header(“HTTP/1.0 200 OK”);
$uri_parts = explode(‘/’, $_SERVER['REQUEST_URI']);
$input = intval($uri_parts[count($uri_parts)-1]);
if(is_int($input) && $input>0){
echo drupal_json_encode(node_load($input));
}
exit();
?>

When called like http://mysite/json/5, it checks that the last argument of in the URI is an int (or can be turned into one as the URI is natively a string), loads that node, and then outputs it as JSON. Exit() is called to stop any templates from being applied later(cheap, I know but I’m in a rush here).

Post a Comment

Your email is never shared. Required fields are marked *

*
*