Rewrite json with colors and unescaped slashes

@param string $jsonString
191764
public function writelnJson($jsonString)
    {
        $keyColor = preg_replace('/"(\w+)": /', '<info>$1</info>: ', $jsonString);
        $valColor = preg_replace('/"([^"]+)"/', "<fg=cyan>'$1'</fg=cyan>", $keyColor);

        $this->output->writeln(stripslashes($valColor));
    }
42675
private function normalize($jsonString)
    {
        if (!is_string($jsonString)) {
            throw new \InvalidArgumentException(sprintf(
                'Expected a string, got "%s"',
                gettype($jsonString)
            ));
        }
        $chars = str_split($jsonString);
        $inRight = $inQuote = $inFakeQuote = false;
        $fakeQuoteStart = null;

        if (empty($chars)) {
            return;
        }

        if ($chars[0] !== '{') {
            array_unshift($chars, '{');
            $chars[] = '}';
        }

        for ($index = 0; $index < count($chars); $index++) {
            $char = $chars[$index];
            $prevChar = isset($chars[$index - 1]) ? $chars[$index - 1] : null;

            if (!$inQuote && $prevChar == ':') {
                $inRight = true;
            }

            if (!$inQuote && preg_match('{\{,}', $char)) {
                $inRight = false;
            }

            // detect start of unquoted string
            if (!$inQuote && preg_match('{[\$a-zA-Z0-9]}', $char)) {
                array_splice($chars, $index, 0, '"');
                $fakeQuoteStart = $index;
                $index++;
                $inQuote = $inFakeQuote = true;

                continue;
            }

            // if we added a "fake" quote, look for the end of the unquoted string
            if ($inFakeQuote && preg_match('{[\s:\}\],]}', $char)) {

                // if we are on the left side, then "]" is OK.
                if (!$inRight && $char === ']') {
                    continue;
                }

                if ($inRight) {

                    // extract the right hand value
                    $string = implode('', array_slice($chars, $fakeQuoteStart + 1, $index - 1 - $fakeQuoteStart));

                    // if it is a number, then we don't quote it
                    if (is_numeric($string)) {
                        unset($chars[$fakeQuoteStart]);
                        $chars = array_values($chars);
                        $inQuote = $inFakeQuote = false;
                        $index--;

                        continue;
                    }

                    // if it is a boolean, then we don't quote it
                    if (in_array($string, ['true', 'false'])) {
                        unset($chars[$fakeQuoteStart]);
                        $chars = array_values($chars);
                        $inQuote = $inFakeQuote = false;
                        $index--;

                        continue;
                    }
                }

                // add the ending quote
                array_splice($chars, $index, 0, '"');
                $index++;
                $inQuote = $inFakeQuote = false;

                continue;
            }

            // enter standard quote mode
            if (!$inQuote && $char === '"') {
                $inQuote = true;

                continue;
            }

            // if we are in quote mode and encounter a closing quote, and the last character
            // was not the escape character
            if ($inQuote && $char === '"' && $prevChar !== '\\') {
                $inQuote = $inFakeQuote = false;

                continue;
            }
        }

        // if we were in a fake quote and hit the end, then add the closing quote
        if ($inFakeQuote) {
            $chars[] = '"';
        }

        $normalized = implode('', $chars);

        return $normalized;
    }
839871
def json_escape_string(s)
      return s if s !~ /["\\\b\f\n\r\t]/

      result = ""
      s.split("").each do |c|
        case c
        when '"', "\\"
          result << "\\" << c
        when "\n" then result << "\\n"
        when "\t" then result << "\\t"
        when "\r" then result << "\\r"
        when "\f" then result << "\\f"
        when "\b" then result << "\\b"
        else
          result << c
        end
      end
      result
    end
1233782
protected function _jsonEncode($in, $indent = 0)
    {
        $out = '';

        foreach ($in as $key => $value) {

            $out .= str_repeat("    ", $indent + 1);
            $out .= json_encode((string)$key) . ': ';

            if (is_object($value) || is_array($value)) {
                $out .= $this->_jsonEncode($value, $indent + 1);
            } else {
                $out .= json_encode($value);
            }

            $out .= "," . PHP_EOL;
        }

        if (!empty($out)) {
            $out = substr($out, 0, -2);
        }

        $out = "{" . PHP_EOL . $out . PHP_EOL . str_repeat("    ", $indent) . "}";

        return $out;
    }
1178951
protected function jsonDecode($json)
    {
        $content = json_decode((string) $json, true);
        $this->handleJsonError(json_last_error());
        
        return $content;
    }
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;
  }
208107
def prettify_json(json_string):
    """"""
    try:
        data = json.loads(json_string)
        html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'
    except:
        html = json_string
    return mark_safe(html)
247439
public static function createFromJsonResponse($jsonString)
    {
        $data = json_decode($jsonString, true);
        if (\is_array($data) && isset($data['items'])) {
            return array_map(function ($membership) {
                return self::getObjectFromArray($membership);
            }, $data['items']);
        }

        return self::getObjectFromArray($data);
    }
627615
protected function setCleanUrl($urlString)
    {
        $arrayToReplace = [
            '&#038;'    => '&amp;',
            '&'         => '&amp;',
            '&amp;amp;' => '&amp;',
            ' '         => '%20',
        ];
        $kys            = array_keys($arrayToReplace);
        $vls            = array_values($arrayToReplace);
        return str_replace($kys, $vls, filter_var($urlString, FILTER_SANITIZE_URL));
    }
62649
public static function format( $json, $validateSource = FALSE )
	{
		$tab			= "  ";
		$content		= "";
		$indentLevel	= 0;
		$inString		= FALSE;

		if( !is_string( $json ) )
			$json	= json_encode( $json );

		if( $validateSource )
			if( json_decode( $json ) === FALSE )
				throw new InvalidArgumentException( 'JSON String is not valid.' );
			
		$len	= strlen( $json );
		for( $c=0; $c<$len; $c++ )
		{
			$char	= $json[$c];
			switch( $char )
			{
				case '{':
				case '[':
					$content .= $char;
					if( !$inString )
					{
						$content .= "\n".str_repeat( $tab, $indentLevel + 1 );
						$indentLevel++;
					}
					break;
				case '}':
				case ']':
					if( !$inString )
					{
						$indentLevel--;
						$content .= "\n".str_repeat( $tab, $indentLevel );
					}
					$content .= $char;
					break;
				case ',':
					$content .= $inString ? $char : ",\n" . str_repeat( $tab, $indentLevel );
					break;
				case ':':
					$content .= $inString ? $char : ": ";
					break;
				case '"':
					if( $c > 0 && $json[$c-1] != '\\' )
						$inString = !$inString;
				default:
					$content .= $char;
					break;                   
			}
		}
		return $content;
	}
553902
public static function createFromJsonResponse($jsonString)
    {
        $data = json_decode($jsonString, true);

        $sourceImages = array_map(function ($sourceImage) {
            return SourceImage::createFromDecodedJsonResponse($sourceImage);
        }, $data['items']);

        $total = isset($data['total']) ? $data['total'] : 0;
        $links = isset($data['links']) ? $data['links'] : [];
        $cursor = isset($data['cursor']) ? $data['cursor'] : null;

        return new self($sourceImages, $total, $links, $cursor);
    }
565103
public static function decode($jsonString, $assoc = false)
    {
        $json = json_decode($jsonString, $assoc);

        self::handleError(json_last_error());

        return $json;
    }
1195629
protected static function prettyPrint($json)
    {
        $result = '';
        $pos = 0;
        $indentation = '    ';
        $newline = "\n";
        $previousChar = '';
        $outOfQuotes = true;

        // Unescape slashes.
        if (strpos($json, '/')) {
            $json = preg_replace('#\134{1}/#', '/', $json);
        }

        $stringLength = strlen($json);

        for ($i = 0; $i <= $stringLength; $i++) {

            // Grab the next character in the string.
            $char = substr($json, $i, 1);

            if (':' == $previousChar && $outOfQuotes) {
                $result .= ' ';
            }

            // Are we inside a quoted string?
            if ('"' == $char && $previousChar != '\\') {
                $outOfQuotes = !$outOfQuotes;

                // If this character is the end of an element,
                // output a new line and indent the next line.
            } elseif (('}' == $char || ']' == $char) && $outOfQuotes) {
                $result .= $newline;
                $pos --;
                for ($j = 0; $j < $pos; $j++) {
                    $result .= $indentation;
                }
            }

            // 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 .= $indentation;
                }
            }

            $previousChar = $char;
        }

        return $result;
    }
824970
public static String prettyFormatJson(String jsonString) {
        requireNonNull(jsonString, "jsonString is null");
        return JSON.toJSONString(getJSONFromString(jsonString), true);
    }
393565
public static function encode($jsonData)
    {
        $jsonString = json_encode($jsonData);
        // 5.5.0 	The return value on failure was changed from null string to FALSE.
        if (false === $jsonString || 'null' === $jsonString) {
            throw new JsonException('unable to encode JSON');
        }

        return $jsonString;
    }
785631
private function parseJson($jsonString)
    {
        $jsonData = json_decode($jsonString, true);

        if ($jsonData === null) {
            $this->emit('error', [json_last_error_msg()]);
            return;
        }

        $this->setContent($jsonString);
        $this->setData($jsonData);
        $this->emit('end');
    }
187161
protected function prettyJson($data)
	{
		$json = json_encode($data, Arr::get($this->config, 'json.encode.options', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP));

		if (json_last_error() !== JSON_ERROR_NONE)
		{
			return false;
		}

		$tab = "\t";
		$newline = "\n";
		$new_json = "";
		$indent_level = 0;
		$in_string = false;
		$len = strlen($json);

		for ($c = 0; $c < $len; $c++)
		{
			$char = $json[$c];
			switch($char)
			{
				case '{':
				case '[':
					if ( ! $in_string)
					{
						$new_json .= $char.$newline.str_repeat($tab, $indent_level+1);
						$indent_level++;
					}
					else
					{
						$new_json .= $char;
					}
					break;
				case '}':
				case ']':
					if ( ! $in_string)
					{
						$indent_level--;
						$new_json .= $newline.str_repeat($tab, $indent_level).$char;
					}
					else
					{
						$new_json .= $char;
					}
					break;
				case ',':
					if ( ! $in_string)
					{
						$new_json .= ','.$newline.str_repeat($tab, $indent_level);
					}
					else
					{
						$new_json .= $char;
					}
					break;
				case ':':
					if ( ! $in_string)
					{
						$new_json .= ': ';
					}
					else
					{
						$new_json .= $char;
					}
					break;
				case '"':
					if ($c > 0 and $json[$c-1] !== '\\')
					{
						$in_string = ! $in_string;
					}
				default:
					$new_json .= $char;
					break;
			}
		}

		return $new_json;
	}