function drupal_json_encode_helper($var) { switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; // Lowercase necessary! // Lowercase necessary! case 'integer': case 'double': return $var; case 'resource': case 'string': // Always use Unicode escape sequences (\u0022) over JSON escape // sequences (\") to prevent browsers interpreting these as // special characters. $replace_pairs = array('\\' => '\\u005C', '"' => '\\u0022', "" => '\\u0000', "" => '\\u0001', "" => '\\u0002', "" => '\\u0003', "" => '\\u0004', "" => '\\u0005', "" => '\\u0006', "" => '\\u0007', "" => '\\u0008', "\t" => '\\u0009', "\n" => '\\u000A', "\v" => '\\u000B', "\f" => '\\u000C', "\r" => '\\u000D', "" => '\\u000E', "" => '\\u000F', "" => '\\u0010', "" => '\\u0011', "" => '\\u0012', "" => '\\u0013', "" => '\\u0014', "" => '\\u0015', "" => '\\u0016', "" => '\\u0017', "" => '\\u0018', "" => '\\u0019', "" => '\\u001A', "" => '\\u001B', "" => '\\u001C', "" => '\\u001D', "" => '\\u001E', "" => '\\u001F', "'" => '\\u0027', '<' => '\\u003C', '>' => '\\u003E', '&' => '\\u0026', '/' => '\\u002F', " " => '\\u2028', " " => '\\u2029'); return '"' . strtr($var, $replace_pairs) . '"'; case 'array': // Arrays in JSON can't be associative. If the array is empty or if it // has sequential whole number keys starting with 0, it's not associative // so we can go ahead and convert it as an array. if (empty($var) || array_keys($var) === range(0, sizeof($var) - 1)) { $output = array(); foreach ($var as $v) { $output[] = drupal_json_encode_helper($v); } return '[ ' . implode(', ', $output) . ' ]'; } // Otherwise, fall through to convert the array as an object. // Otherwise, fall through to convert the array as an object. case 'object': $output = array(); foreach ($var as $k => $v) { $output[] = drupal_json_encode_helper(strval($k)) . ':' . drupal_json_encode_helper($v); } return '{' . implode(', ', $output) . '}'; default: return 'null'; } }
/** * Clones drupal_json_encode from common.inc. * * PHP's json_encode() was not available before 5.2.0. * Drupal 7 uses the version from PHP 5.3 or clones it. * * @param $var * The data to encode. * * @return string * A json string representation of $var. */ function chatblock_to_js($var) { if (version_compare(PHP_VERSION, '5.3.0', '>=')) { // 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 'includes/json-encode.inc'; return drupal_json_encode_helper($var); }