7.x common.inc drupal_json_encode($var)

Converts a PHP variable into its JavaScript equivalent.

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

See also



Related topics

6 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_get_js in includes/common.inc
Returns a themed presentation of all JavaScript code for the current page.
drupal_json_output in includes/common.inc
Returns data in JSON format.
TaxonomyTermTestCase::testTermAutocompletion in modules/taxonomy/taxonomy.test
Tests term autocompletion edge cases with slashes in the names.

... See full list


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


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);


jhodgdon’s picture

alagar’s picture

Hi there
since PHP 5.3 json_encode supports escaping '<', '>' and '&' json_encode() see options parameter.

so this function can be rewrite as

function drupal_json_encode($var) {
  return  json_encode($var,JSON_HEX_TAG|JSON_HEX_AMP));
weboide’s picture

Be careful when you wish to output json arrays only, but you are also using functions like array_unique (other functions that preserve keys certainly behave the same way).

$a = array('one', 'two', 'two', 'three');


Make sure you pass the array to array_values, before passing it to drupal_json_output.

$a = array('one', 'two', 'two', 'three');


j0rd’s picture

Is there a jQuery equivalent of this function?

jQuery while it does have a function for parseJSON(), does not include one to encodeJSON(). This means in jQuery you can not call a function to turn an array into a jsonString with out doing it manually.

If anyone knows, please post.
Drupal Commerce Themes & Development

vatavale’s picture

For encode arrays to JSON use jQuery-JSON plugin (2kb) http://code.google.com/p/jquery-json/
Than you can use jQuery.toJSON()