1 common.inc backdrop_json_format($json)

Format a string of JSON for older versions of PHP.

Parameters

$json: A string of JSON text.

Return value

string: A formatted string of JSON text.

File

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

Code

function backdrop_json_format($json) {
  // This code adopted from
  // https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.php.

  $result = '';
  $pos = 0; // Indentation level.
  $strlen = strlen($json);
  $indent = "    ";
  $new_line = "\n";
  $prev_char = '';
  $prev_prev_char = '';
  $out_of_quotes = TRUE;

  for ($i = 0; $i < $strlen; $i++) {
    // Grab the next character in the string.
    $char = substr($json, $i, 1);

    // Are we inside a quoted string?
    if ($char === '"' && !($prev_char === '\\' && $prev_prev_char !== '\\')) {
      $out_of_quotes = !$out_of_quotes;
    }
    // If this character is the end of an element, output a new line and indent
    // the next line.
    elseif (($char == '}' || $char == ']') && $out_of_quotes) {
      $result .= $new_line;
      $pos--;
      for ($j = 0; $j < $pos; $j++) {
        $result .= $indent;
      }
    }
    // Eat all non-essential whitespace in the input as we do our own here and
    // it would only mess up our process.
    elseif ($out_of_quotes && FALSE !== strpos(" \t\r\n", $char)) {
      continue;
    }

    // Add the character to the result string.
    $result .= $char;
    // Always add a space after a field colon:
    if ($char == ':' && $out_of_quotes) {
      $result .= ' ';
    }

    // If the last character was the beginning of an element, output a new line
    // and indent the next line.
    if (($char == ',' || $char == '{' || $char == '[') && $out_of_quotes) {
      $result .= $new_line;
      if ($char == '{' || $char == '[') {
        $pos++;
      }
      for ($j = 0; $j < $pos; $j++) {
        $result .= $indent;
      }
    }
    $prev_prev_char = $prev_char;
    $prev_char = $char;
  }

  return $result;
}