Это решение делает JSON действительно красивым. Не совсем то, о чем просил OP, но он позволяет лучше визуализировать JSON.
/**
* takes an object parameter and returns the pretty json format.
* this is a space saving version that uses 2 spaces instead of the regular 4
*
* @param $in
*
* @return string
*/
function pretty_json ($in): string
{
return preg_replace_callback('/^ +/m',
function (array $matches): string
{
return str_repeat(' ', strlen($matches[0]) / 2);
}, json_encode($in, JSON_PRETTY_PRINT | JSON_HEX_APOS)
);
}
/**
* takes a JSON string an adds colours to the keys/values
* if the string is not JSON then it is returned unaltered.
*
* @param string $in
*
* @return string
*/
function markup_json (string $in): string
{
$string = 'green';
$number = 'darkorange';
$null = 'magenta';
$key = 'red';
$pattern = '/("(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/';
return preg_replace_callback($pattern,
function (array $matches) use ($string, $number, $null, $key): string
{
$match = $matches[0];
$colour = $number;
if (preg_match('/^"/', $match))
{
$colour = preg_match('/:$/', $match)
? $key
: $string;
}
elseif ($match === 'null')
{
$colour = $null;
}
return "<span style='color:{$colour}'>{$match}</span>";
}, str_replace(['<', '>', '&'], ['<', '>', '&'], $in)
) ?? $in;
}
public function test_pretty_json_object ()
{
$ob = new \stdClass();
$ob->test = 'unit-tester';
$json = pretty_json($ob);
$expected = <<<JSON
{
"test": "unit-tester"
}
JSON;
$this->assertEquals($expected, $json);
}
public function test_pretty_json_str ()
{
$ob = 'unit-tester';
$json = pretty_json($ob);
$this->assertEquals("\"$ob\"", $json);
}
public function test_markup_json ()
{
$json = <<<JSON
[{"name":"abc","id":123,"warnings":[],"errors":null},{"name":"abc"}]
JSON;
$expected = <<<STR
[
{
<span style='color:red'>"name":</span> <span style='color:green'>"abc"</span>,
<span style='color:red'>"id":</span> <span style='color:darkorange'>123</span>,
<span style='color:red'>"warnings":</span> [],
<span style='color:red'>"errors":</span> <span style='color:magenta'>null</span>
},
{
<span style='color:red'>"name":</span> <span style='color:green'>"abc"</span>
}
]
STR;
$output = markup_json(pretty_json(json_decode($json)));
$this->assertEquals($expected,$output);
}
}
up_json_encode($data, JSON_PRETTY_PRINT);