1 common.inc backdrop_json_encode($var, $pretty_print = FALSE)

Converts a PHP variable into its JavaScript equivalent.

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

Parameters

mixed $var: The variable to be encoded as JSON.

bool $pretty_print: Backwards-compatible pretty printing of the JSON string. This uses the JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE options to make the JSON more readable by humans, or emulates this functionality if running an older version of PHP.

Return value

string: The given $var encoded as a JSON string.

See also

backdrop_json_decode()

Related topics

File

core/includes/common.inc, line 5710
Common functions that many Backdrop modules will need to reference.

Code

function backdrop_json_encode($var, $pretty_print = FALSE) {
  if ($pretty_print) {
    return json_encode($var, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  }
  // The non-pretty JSON is HTML markup compatible, encoding <, >, ', &, and ".
  else {
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }
}