[PHP] json pretty print

PHP 2014. 3. 18. 09:58



json 형식의 문자열을 사람이 알아볼 수 있도록 출력하기 위한 함수.

PHP 5.4 이상은 json_encode의 option 중에 JSON_PRETTY_PRINT가 있으나,

하위 버전에서 json을 예쁘게 출력하기 위해선 아래와 같은 함수가 필요함.



function prettyPrint( $json )

{

    $result = '';

    $level = 0;

    $prev_char = '';

    $in_quotes = 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( $char === '"' && $prev_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;

            }

        }

        if( $new_line_level !== NULL ) {

            $result .= "\n".str_repeat( "\t", $new_line_level );

        }

        $result .= $char.$post;

        $prev_char = $char;

    }


    return $result;

}





[참조]

http://www.php.net/json_encode

http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php





Posted by bloodguy
,