You are here

function mediafront_json_encode in MediaFront 6

Same name and namespace in other branches
  1. 6.2 mediafront.module \mediafront_json_encode()

Converts a PHP variable into its Javascript equivalent.

Almost identical to the drupal_to_js routine, but there was an issue that I found with this method where a "Parse Error" was caused. See http://drupal.org/node/807376 To keep any dependencies on people upgrading to that patch, I am just re-implementing it here with the patch in place.

4 calls to mediafront_json_encode()
mediafront_get_node_json in ./mediafront.module
Gets a node in JSON format
mediafront_get_playlist_json in ./mediafront.module
Gets a playlist in JSON format.
mediafront_views_pre_render in ./mediafront.module
Views pre-render
osmplayer_get_player in players/osmplayer/osmplayer.module
Implementation of hook_get_player()

File

./mediafront.module, line 282

Code

function mediafront_json_encode($var) {
  switch (gettype($var)) {
    case 'boolean':
      return $var ? 'true' : 'false';

    // Lowercase necessary!
    case 'integer':
    case 'double':
      return $var;
    case 'resource':
    case 'string':
      return '"' . str_replace(array(
        "\r",
        "\n",
        "<",
        ">",
        "&",
        "\\'",
      ), array(
        '\\r',
        '\\n',
        '\\x3c',
        '\\x3e',
        '\\x26',
        "'",
      ), addslashes($var)) . '"';
    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[] = mediafront_json_encode($v);
        }
        return '[' . implode(',', $output) . ']';
      }

    // Otherwise, fall through to convert the array as an object.
    case 'object':
      $output = array();
      foreach ($var as $k => $v) {
        $output[] = mediafront_json_encode(strval($k)) . ': ' . mediafront_json_encode($v);
      }
      return '{' . implode(',', $output) . '}';
    default:
      return 'null';
  }
}