【发布时间】:2020-03-11 00:00:28
【问题描述】:
尝试漂亮地打印 json,并且工作正常,cept,似乎在打印每个对象数组之间的对象数组时添加了额外的一行。可以对这个逻辑使用一些帮助,因为我有一段时间没有触及这个......
漂亮的打印代码如下:
public function pretty_print($json_data, $line_numbers = true)
{
$return = '';
$space = 0;
$flag = false;
$json_data = trim($json_data);
$line = 1;
if (!empty($json_data)) {
if (!empty($line_numbers))
$return .= '<div class="line" data-line-number="' . $line . '">';
//loop for iterating the full json data
for($counter = 0; $counter < strlen($json_data); $counter++)
{
//Checking ending second and third brackets
if ($json_data[$counter] == '}' || $json_data[$counter] == ']')
{
$space--;
$line++;
$return .= !empty($line_numbers) ? '</div><div class="line" data-line-number="' . $line . '">' : PHP_EOL;
$return .= str_repeat(' ', ($space*4));
}
//Checking for double quote(“) and comma (,)
if ($json_data[$counter] == '"' && ((!empty($counter) && $json_data[$counter-1] == ',') || ($counter > 1 && $json_data[$counter-2] == ',')))
{
$line++;
$return .= !empty($line_numbers) ? '</div><div class="line" data-line-number="' . $line . '">' : PHP_EOL;
$return .= str_repeat(' ', ($space*4));
}
if ($json_data[$counter] == '"' && !$flag)
{
if ( (!empty($counter) && $json_data[$counter-1] == ':') || ($counter > 1 && $json_data[$counter-2] == ':' ))
$return .= ' <span class="json-property">';
else
$return .= '<span class="json-value">';
}
$return .= $json_data[$counter];
//Checking conditions for adding closing span tag
if ($json_data[$counter] == '"' && $flag) {
$return .= '</span>';
}
if ($json_data[$counter] == '"')
$flag = !$flag;
//Checking starting second and third brackets
if ($json_data[$counter] == '{' || $json_data[$counter] == '[')
{
$space++;
$line++;
$return .= !empty($line_numbers) ? '</div><div class="line" data-line-number="' . $line . '">' : PHP_EOL;
$return .= str_repeat(' ', ($space*4));
}
}
if (!empty($line_numbers))
$return .= '</div>';
}
return !empty($return) ? trim($return) : json_encode(json_decode($json_data, true), JSON_PRETTY_PRINT);
}
但似乎用额外的<div class="line" data-line-number=""></div> 解析 json
这是一张图片,如果可能的话,想去掉数组对象之间的额外空间。如有任何帮助,将不胜感激。
【问题讨论】:
-
这让我觉得这是一个可以通过递归更好地解决的问题。
-
为什么不直接使用内置功能呢?
echo json_encode(json_decode($json_data), JSON_PRETTY_PRINT);如果你有原始数据,你可以跳过json_decode($json_data)步骤。 -
@Nick - 因为我需要图像中的样式和数字。所以,
JSON_PRETTY_PRINT不提供这种能力。 -
@AlexBarker - 会对您的处理方法非常感兴趣。正在考虑同样的事情,但是,我一直在这个问题上碰壁。如果你有时间,会对一个简短的例子感兴趣吗?干杯 :) 如果需要示例,可以在此处下载 json 文件:dropbox.com/s/59bnd6h3nkacjcd/eventlog-json.json?dl=0
-
@SolomonClosson 你有原始数据,还是只有 JSON?
标签: php json pretty-print