You are here

function drupal_json_encode in Drupal 7

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 includes/ajax.inc
Renders a commands array into JSON.
DrupalJSONTest::testJSON in modules/simpletest/tests/common.test
Tests converting PHP variables to JSON strings and back.
drupal_pre_render_scripts in includes/common.inc
The #pre_render callback for the "scripts" element.
TaxonomyTermTestCase::testTermAutocompletion in modules/taxonomy/taxonomy.test
Tests term autocompletion edge cases with slashes in the names.
_locale_rebuild_js in includes/locale.inc
(Re-)Creates the JavaScript translation file for a language.

File

includes/common.inc, line 5237
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);
}