Нашел функциию в интернете и слегка доработал её под свой стиль.
<?php
/**
* Indents a flat JSON string to make it more human-readable.
*
* @param string $json The original JSON string to process.
*
* @return string Indented version of the original JSON string.
*/
function json_indent($json, $indentStr = " ", $newLine = "n")
{
$ind = 0; // Current indention width
$result = ""; // Resulting string
$indention = ""; // Current indention after newline
$escaped = false; // FALSE or escape character
$strLen = strlen($json);
for($i = 0; $i < $strLen; $i++)
{
// Grab the next character in the string
$char = $json[$i];
if($escaped)
{
if($escaped == $char)
{
// End of escaped sequence
$escaped = false;
}
$result .= $char;
if ($char == "\\" && $i + 1 < $strLen)
{
// Next character will NOT end this sequence
$result .= $json[++$i];
}
continue;
}
if ($char == '"' || $char == "'")
{
// Escape this string
$escaped = $char;
$result .= $char;
continue;
}
if(($char == '{' || $char == '[') )
{
$indention = str_repeat($indentStr, $ind++);
if($i > 0 && $json[$i-1] != "," && $json[$i-1] != "[" && $json[$i-1] != "{")
{
$result .= $newLine . $indention;
}
}
// If this character is the end of an element,
// output a new line and indent the next line
if ($char == '}' || $char == ']')
{
$indention = str_repeat($indentStr, --$ind);
$result .= $newLine . $indention;
}
// Add the character to the result string
if($char == ":")
{
$result .= " $char ";
}
else
{
$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 == '[')
{
if ($char == '{' || $char == '[')
{
$indention = str_repeat($indentStr, $ind);
}
$result .= $newLine . $indention;
}
}
return $result;
}
Печатает примерно такое:
{
"fileCount" : 2,
"data" :
[
{
"id" : "file.1",
"class" : "file",
"file" : "example_file.1.html",
"display" : "example_file.1",
"extension" : "html",
"size" : 12345,
"hasVersions" : true,
"versions" :
{
"fileCount" : 1,
"data" :
[
{
"id" : "file.1.1",
"class" : "file",
"file" : "example_file.1.1.html",
"display" : "example_file.1.1",
"extension" : "html",
"size" : 12345,
"hasVersions" : false,
"versions" : null
}
]
}
},
{
"id" : "file.2",
"class" : "file",
"file" : "example_file.2.html",
"display" : "example_file.2",
"extension" : "html",
"size" : 12345,
"hasVersions" : false,
"versions" : null
}
]
}