Pretty-Printing JSON with PHP

2022-08-30 05:47:29

我正在构建一个PHP脚本,它将JSON数据馈送到另一个脚本。我的脚本将数据构建到一个大型关联数组中,然后使用 输出数据。下面是一个示例脚本:json_encode

$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);

上面的代码产生以下输出:

{"a":"apple","b":"banana","c":"catnip"}

如果你有少量数据,这很好,但我更喜欢这样的东西:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

有没有办法在PHP中做到这一点,而不会有丑陋的黑客攻击?Facebook似乎有人想通了。


答案 1

PHP 5.4 提供了用于调用的选项。JSON_PRETTY_PRINTjson_encode()

http://php.net/manual/en/function.json-encode.php

<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);

答案 2

此函数将采用 JSON 字符串并将其缩进,使其非常可读。它也应该是收敛的,

prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

输入

{"key1":[1,2,3],"key2":"value"}

输出

{
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"
}

法典

function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}

推荐