Pretty-print JSON string

Use 'indent' option to select indentation string - by default it's a tab

@param string $json Original JSON string
@param array $options Encoding options
@return string
6260
public static function prettyPrint($json, $options = array())
    {
        $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
        $result = "";
        $indent = 0;

        $ind = "    ";
        if (isset($options['indent'])) {
            $ind = $options['indent'];
        }

        $inLiteral = false;
        foreach ($tokens as $token) {
            $token = trim($token);
            if ($token == "") {
                continue;
            }

            if (preg_match('/^("(?:.*)"):[ ]?(.*)$/', $token, $matches)) {
                $token = $matches[1] . ': ' . $matches[2];
            }

            $prefix = str_repeat($ind, $indent);
            if (!$inLiteral && ($token == "{" || $token == "[")) {
                $indent++;
                if ($result != "" && $result[strlen($result)-1] == "\n") {
                    $result .= $prefix;
                }
                $result .= "$token\n";
            } elseif (!$inLiteral && ($token == "}" || $token == "]")) {
                $indent--;
                $prefix = str_repeat($ind, $indent);
                $result .= "\n$prefix$token";
            } elseif (!$inLiteral && $token == ",") {
                $result .= "$token\n";
            } else {
                $result .= ($inLiteral ?  '' : $prefix) . $token;

                //remove escaped backslash sequences causing false positives in next check
                $token = str_replace('\\', '', $token);
                // Count # of unescaped double-quotes in token, subtract # of
                // escaped double-quotes and if the result is odd then we are
                // inside a string literal
                if ((substr_count($token, '"')-substr_count($token, '\\"')) % 2 != 0) {
                    $inLiteral = !$inLiteral;
                }
            }
        }
        return $result;
    }
429355
public static function get_Json( &$json )
    {
        if( $json instanceof Json ) {
            return $json;
        }
        return !is_null($json)
            ? new Json($json)
            : null
            ;
    }
154192
public static function render($options)
    {
        $jsExpressions = array();
        //Replace any js expression with random strings so we can switch
        //them back after json_encode the options
        $options = static::_replaceJsExpr($options, $jsExpressions);

        //TODO: Check for encoding errors
        $result = json_encode($options);

        //Replace any js expression on the json_encoded string
        foreach ($jsExpressions as $key => $expr) {
            $result = str_replace('"' . $key . '"', $expr, $result);
        }
        return $result;
    }
203418
public static function convertImageJson($json): string
    {
        if (empty($json))
            return "";
        elseif (is_array($json) && !empty($json[0]['url']))
            return HOME . str_replace('\\', '/', $json[0]['url']);
        elseif (Check::isJson($json) && preg_match('/url/i', $json))
            return HOME . str_replace('\\', '/', json_decode($json, true)[0]['url']);

        return "";
    }
80759
def format_json(json_object, indent):
    
    indent_str = "\n" + " " * indent
    json_str = json.dumps(json_object, indent=2, default=serialize_json_var)
    return indent_str.join(json_str.split("\n"))
932475
public function prettyPrint($json) {
    $result      = '';
    $pos         = 0;
    $strLen      = mb_strlen($json);
    $indentStr   = '  ';
    $newLine     = "\n";
    $prevChar    = '';
    $outOfQuotes = 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 == '"' && $prevChar != '\\') {
            $outOfQuotes = !$outOfQuotes;
        
        // If this character is the end of an element, 
        // output a new line and indent the next line.
        } else if(($char == '}' || $char == ']') && $outOfQuotes) {
            $result .= $newLine;
            $pos --;
            for ($j=0; $j<$pos; $j++) {
                $result .= $indentStr;
            }
        }
        
        // Add the character to the result string.
        $result .= $char;

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

    return $result;
  }
727798
def _format_json(self, ans, q):
        
        params = {}
        try: params['indent'] = int(q.get('indent')[0])
        except: pass

        return json.dumps(ans, **params)+'\n'
791282
public function debug_decode($json,$assoc=false,$depth=512,$options=0){
			$test = json_decode($json,$assoc,$depth,$options);
			if (!empty($test)) $json = $test;
			$data = $this->errorMessage(json_last_error(),$json);
			return json_encode($data,JSON_PRETTY_PRINT);
		}
82388
public static function encode($value, $options = null)
    {
        if ($options === null) {
            $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT;
        }

        $json = json_encode($value, $options);

        static::handleJsonError(json_last_error());

        return $json;
    }
1017383
protected function jsonDecode($json)
    {
        // From firebase/php-jwt
        if (!(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
            /**
             * In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
             * to specify that large ints (like Steam Transaction IDs) should be treated as
             * strings, rather than the PHP default behaviour of converting them to floats.
             */
            $obj = json_decode($json, false, 512, JSON_BIGINT_AS_STRING);
        } else {
            // @codeCoverageIgnoreStart
            /**
             * Not all servers will support that, however, so for older versions we must
             * manually detect large ints in the JSON string and quote them (thus converting
             * them to strings) before decoding, hence the preg_replace() call.
             * Currently not sure how to test this so I ignored it for now.
             */
            $maxIntLength = strlen((string) PHP_INT_MAX) - 1;
            $jsonWithoutBigints = preg_replace('/:\s*(-?\d{'.$maxIntLength.',})/', ': "$1"', $json);
            $obj = json_decode($jsonWithoutBigints);
            // @codeCoverageIgnoreEnd
        }

        return $obj;
    }
487141
public static function encode($data, $options = 0): string
    {
        $json = json_encode($data, $options);
        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new JsonEncodeException(json_last_error_msg());
        }

        return $json;
    }
1178951
protected function jsonDecode($json)
    {
        $content = json_decode((string) $json, true);
        $this->handleJsonError(json_last_error());
        
        return $content;
    }
288522
private function simple_json_parser($json){
        $json = str_replace("{","",str_replace("}","", $json));
        $jsonValue = explode(",", $json);
        $arr = array();
        foreach($jsonValue as $v){
            $jValue = explode(":", $v);
            $arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
        }
        return $arr;
    }
473295
public static final String format(String json) {
		final int len = json.length();
		if (len < 3) {
			return json;
		}
		final StringTokenizer st = new StringTokenizer(json, ",{}[]", true);
		final StringBuilder out = new StringBuilder(len * 2);
		String token;
		int indent = 0;
		while (st.hasMoreTokens()) {
			token = st.nextToken();
			if ("{".equals(token) || "[".equals(token)) {
				indent++;
				out.append(token);
				appendIndent(out, indent);
				continue;
			}
			if ("}".equals(token) || "]".equals(token)) {
				indent--;
				appendIndent(out, indent);
				out.append(token);
				continue;
			}
			if (",".equals(token)) {
				out.append(',');
				appendIndent(out, indent);
				continue;
			}
			out.append(token);
		}
		return out.toString();
	}
1003637
protected function jsonEncode($element): string
    {
        $json = json_encode($element, $this->options);

        if ($json === false) {
            trigger_error("JSON encode failed; " . json_last_error_msg(), E_USER_WARNING);
            return json_encode(null);
        }

        // Indent for pretty print
        if (($this->options & \JSON_PRETTY_PRINT) > 0 && (~$this->options & self::OUTPUT_LINES) > 0) {
            $json = rtrim("    " . str_replace("\n", "\n    ", $json));
        }

        return $json;
    }
928227
public static function encode(
        $value,
        $options = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION
    ) {
        $json = \json_encode($value, $options);
        if (JSON_ERROR_NONE !== ($error = \json_last_error())) {
            throw new JsonException(\json_last_error_msg(), $error);
        }

        return $json;
    }
386513
public static function image($json): string
    {
        if (empty($json))
            return "";

        if (defined("HOME")) {
            if (is_array($json) && !empty($json[0]['url']))
                return HOME . str_replace('\\', '/', $json[0]['url']);
            elseif (Validate::json($json) && preg_match('/url/i', $json))
                return HOME . str_replace('\\', '/', json_decode($json, true)[0]['url']);
            elseif (is_string($json))
                return HOME . $json;
        }
        return "";
    }