Pretty-Printing JSON with PHP

后端 未结 24 1864
一向
一向 2020-11-22 02:03

I\'m building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode

24条回答
  •  忘了有多久
    2020-11-22 02:43

    Classic case for a recursive solution. Here's mine:

    class JsonFormatter {
        public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
            $inString = $escaped = false;
            $result = $indent;
    
            if(is_string($j)) {
                $bak = $j;
                $j = str_split(trim($j, '"'));
            }
    
            while(count($j)) {
                $c = array_shift($j);
                if(false !== strpos("{[,]}", $c)) {
                    if($inString) {
                        $result .= $c;
                    } else if($c == '{' || $c == '[') {
                        $result .= $c."\n";
                        $result .= self::prettyPrint($j, $indentor, $indentor.$indent);
                        $result .= $indent.array_shift($j);
                    } else if($c == '}' || $c == ']') {
                        array_unshift($j, $c);
                        $result .= "\n";
                        return $result;
                    } else {
                        $result .= $c."\n".$indent;
                    } 
                } else {
                    $result .= $c;
                    $c == '"' && !$escaped && $inString = !$inString;
                    $escaped = $c == '\\' ? !$escaped : false;
                }
            }
    
            $j = $bak;
            return $result;
        }
    }
    

    Usage:

    php > require 'JsonFormatter.php';
    php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
    php > print_r($a);
    Array
    (
        [foo] => 1
        [bar] => This "is" bar
        [baz] => Array
            (
                [a] => 1
                [b] => 2
                [c] => "3"
            )
    
    )
    php > echo JsonFormatter::prettyPrint(json_encode($a));
    {
        "foo":1,
        "bar":"This \"is\" bar",
        "baz":{
            "a":1,
            "b":2,
            "c":"\"3\""
        }
    }
    

    Cheers

提交回复
热议问题