function drupal_json_output

You are here

7 common.inc drupal_json_output($var = NULL)

Returns data in JSON format.

This function should be used for JavaScript callback functions returning data in JSON format. It sets the header for JavaScript output.

Parameters

$var: (optional) If set, the variable will be converted to JSON and output.

21 calls to drupal_json_output()
database_test_db_query_temporary in modules/simpletest/tests/database_test.module
Run a db_query_temporary and output the table name and its number of rows.
database_test_even_pager_query in modules/simpletest/tests/database_test.module
Run a pager query and return the results.
database_test_odd_pager_query in modules/simpletest/tests/database_test.module
Run a pager query and return the results.
database_test_tablesort in modules/simpletest/tests/database_test.module
Run a tablesort query and return the results.
database_test_tablesort_first in modules/simpletest/tests/database_test.module
Run a tablesort query with a second order_by after and return the results.

... See full list

1 string reference to 'drupal_json_output'
system_menu in modules/system/system.module
Implements hook_menu().

File

includes/common.inc, line 5040
Common functions that many Drupal modules will need to reference.

Code

function drupal_json_output($var = NULL) {
  // We are returning JSON, so tell the browser.
  drupal_add_http_header('Content-Type', 'application/json');

  if (isset($var)) {
    echo drupal_json_encode($var);
  }
}

Comments

However, D6 has some bugs about header content-type (not application/json but text/javascript) and breaks validation JSON if you are using jQuery update to 1.4. So use D6 version with care.

For the Drupal 8 equivalent, see http://drupal.org/node/1665684

How to outpt jsonp?

for jsonp callback you can do something like this:

$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);
  header("Content-type: text/javascript");
  echo $callback ."(". $json_response .");";
}
else {
  drupal_json_output($response);
}

As I see in drupal 7 the "Drupal" object doesn't have function like jsonParse.
How can I make JSON output to javascript object?

So you can use the jQuery function $.getJSON() to go fetch your JSON from your view endpoint and call a function when the get is successful. Your JSON will be available as an object.