function drupal_json_encode

Converts a PHP variable into its JavaScript equivalent.

We use HTML-safe strings, with several characters escaped.

See also

drupal_json_decode()

drupal_json_encode_helper()

Related topics

5 calls to drupal_json_encode()
ajax_render in drupal/includes/ajax.inc
Renders a commands array into JSON.
DrupalJSONTest::testJSON in drupal/modules/simpletest/tests/common.test
Tests converting PHP variables to JSON strings and back.
drupal_get_js in drupal/includes/common.inc
Returns a themed presentation of all JavaScript code for the current page.
TaxonomyTermTestCase::testTermAutocompletion in drupal/modules/taxonomy/taxonomy.test
Tests term autocompletion edge cases with slashes in the names.
_locale_rebuild_js in drupal/includes/locale.inc
(Re-)Creates the JavaScript translation file for a language.

File

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

Code

function drupal_json_encode($var) {

  // The PHP version cannot change within a request.
  static $php530;
  if (!isset($php530)) {
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  }
  if ($php530) {

    // Encode <, >, ', &, and " using the json_encode() options parameter.
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }

  // json_encode() escapes <, >, ', &, and " using its options parameter, but
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  return drupal_json_encode_helper($var);
}