I am using a module to encode to json, but it puts out "\u0026" instead of "&".

How can I avoid that?



Content as Json module simply returns the content by running it through drupal_json_output(), which in turn call drupal_json_encode(). Inside drupal_json_encode drupal ensures to have unicode conversion to special characters including '<','>','&'.

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

If you see if your php version is greater than 5.3 than json_encode() it self takes the argument to make sure all are unicode converted, it php is less than or euqall to 5.3, than drupal imcludes a helper json-encode.inc file which do the same.


Way 1: The best would be to handle it on the client consuming the json data, have quivalent parser on the consumer side as well.

Way 2: Hook into contentasjson module to return json the way you want.Alter menu callback to register your own page callback

function mymodule_menu_alter(&$itmes) {
  $item['contentasjson/%/%']['page callback'] = '_my_custom_json_as_content';

//Copy the code as it from contentasjson module `contentasjson_get_data()` callback with a small change the json_encode function.
function _my_custom_json_as_content($type, $id) {
  switch ($type) {
    case "node" :
      $data = _contentasjson_get_node( $id );

    case "comment" :
      $data = _contentasjson_get_comment( $id );

    case "menu" :
      $data = _contentasjson_get_menu( $id );

    case "taxonomy_term" :
      $data = _contentasjson_get_taxonomy_term( $id );

    case "taxonomy_vocabulary" :
      $data = _contentasjson_get_taxonomy_vocabulary( $id );

    case "custom_data" :
      $data = _contentasjson_get_custom_data();

    default :
      $data = _contentasjson_get_error_message_type( $type );

  // If false (no data object returned), generate return message
  $data = ($data == FALSE ? _contentasjson_get_error_message_id( $id ) : $data);
  // Here is the small change we are doing.
  json_encode( $data );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.