| 7 common.inc | drupal_json_encode($var) |
| 8 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
File
- includes/
common.inc, line 4864 - Common functions that many Drupal modules will need to reference.
Code
<?php
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);
}
?> Login or register to post comments
Comments
Drupal 6
The equivalent function in Drupal 6 is http://api.drupal.org/api/function/drupal_to_js/6
See http://drupal.org/update/modules/6/7#rename-drupal-to-js for more information.
json_encode
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));
}
json arrays
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).
<?php$a = array('one', 'two', 'two', 'three');
drupal_json_output(array_unique($a));
?>
returns:
{"0":"one","1":"two","3":"three"}Make sure you pass the array to array_values, before passing it to drupal_json_output.
<?php$a = array('one', 'two', 'two', 'three');
drupal_json_output(array_values(array_unique($a)));
?>
returns:
["one","two","three"]jQuery Equivalent
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
For encode arrays to JSON use
For encode arrays to JSON use jQuery-JSON plugin (2kb) http://code.google.com/p/jquery-json/
Than you can use jQuery.toJSON()