Drupal and JQuery 1.5: Fixing the JSON encoding of ampersands

Drupal 6′s drupal_json method encodes ampersands incorrectly for JQuery 1.5, causing the rather cryptic error:

Uncaught Syntax error, unrecognized expression: ...

(If you’re lucky.)

The way to fix this is to borrow the JSON-handling code from Drupal 7. Here’s something you might be able to use:

function yourmodule_json_encode($var) {
  return str_replace(array('<', '>', '&'), array('\u003c', '\u003e', '\u0026'), $var);
}

// Fix Drupal JSON problems from http://witti.ws/blog/2011/03/14/jquery-15-json-parse-error
function yourmodule_json($var) {
  drupal_set_header('Content-Type: text/javascript; charset=utf-8');
  if (isset($var)) {
    echo yourmodule_json_encode(json_encode($var));
  }
}

Use yourmodule_json instead of drupal_json wherever applicable.

Hat tip to Greg Payne (Witti) for pointing me in the right direction!

2011-08-04 Thu 14:01

  • catch

    Or you could also use/review the core patch at http://drupal.org/node/1086098 that should fix this and several other issues.

  • mikeytown2

    Also take a look at the Advanced CSS/JS Aggregation module; works around the issue as well. Function to call is advagg_drupal_to_js().

  • http://www.innoraft.com Mukesh

    Awesome, this saved my life. The code you have put here is a little incomplete, I guess the problem was with the editor. The json_encode function should be:

    function yourmodule_json_encode($var) {
    return str_replace(array(”, ‘&’), array(”, ‘&’), $var);
    }

    And at the end, wherever you are calling drupal_json, just replace with yourmodule_json ..

    Thanks a ton!

  • http://sachachua.com Sacha Chua

    Oh yeah, hey! Good catch. =) Thanks!