3

I can create JSON output using a menu hook using the drupal_json_output callback.

Example:

$items['page/%/json'] = array(
  'access callback'   => TRUE,
  'page callback'     => '_modulename_json',
  'delivery callback' => 'drupal_json_output'
);

function _modulename_json() {
  return array(
    'item1' => $field_item1[0]['safe_value'],
    'item2' => $field_item2[0]['safe_value'],
    'item3' => $item3,
    );
}

Output:

{"item1":"Field item1 content","item2":"Field item2 content","item3":"Item3 content"}

But I need to have JSONP, and am struggling to find an elegant solution... I have tried the code from the bottom of the API page, it does the padding, but makes a mess of the content.

$response = array(1,2,3);
$callback = check_plain($_REQUEST['callback']);
// If its a jsonp callback request
if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}
else {
  drupal_json_output($response);
}

Output this way:

callbackName({\u0022item1\u0022:\u0022Field item1 content\u0022,\u0022item2\u0022:\u0022Field item2 content\u0022,\u0022item3\u0022:\u0022Item3 content\u0022});"
  • i believe the problem is with line $json_response = drupal_json_encode($response); so that your code is double encoded remove this line and check – DEVARAJ JOHNSON Feb 20 '15 at 14:23
  • The issue is definitely related to this. But without it the output is callbackName(Array); – mediaashley Feb 20 '15 at 14:27
2

The array was being double encoded. First by the $json_response = drupal_json_encode($response); and then again by the menu delivery callback 'delivery callback' => 'drupal_json_output'.

To fix this, remove the delivery callback, and use just 'type' => MENU_CALLBACK,.

In the function change this:

if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}

to this:

if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  drupal_add_http_header('Content-Type', 'application/javascript');
  echo $callback . "(" . $json_response . ");";
  drupal_exit();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.