首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要帮助使用JSON漂亮打印对此逻辑进行排序

需要帮助使用JSON漂亮打印对此逻辑进行排序
EN

Stack Overflow用户
提问于 2019-11-14 21:25:02
回答 1查看 132关注 0票数 0

当打印出每个对象数组之间的对象数组时,试图漂亮地打印json,并且工作得很好,cept似乎增加了一条额外的行。我已经有一段时间没碰过这个了.

漂亮打印的代码如下:

代码语言:javascript
复制
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。

这里有一个图像,如果可能的话,希望去掉数组对象之间的额外空间。这里的任何帮助都会很感激的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-15 00:34:16

你为什么要手动解析JSON呢?该代码将非常难以推理和维护,特别是当您稍后返回到它时,几乎不可避免地会出现一个bug。

与其采取困难的做法,不如考虑采取以下措施:

  1. 重新格式化JSON,使其适合您的需要。例如,在本例中,您更喜欢将对象的结束括号和结束括号保持在同一行上,而不是在单独的行上。
  2. 将已经格式化良好的JSON拆分成单独的行。
  3. 用HTML.
  4. 重新加入这些行,以获得最终的HTML.

代码语言:javascript
复制
function prettyWrapJson($json_data, $line_numbers = true) {
    // Ensure that our JSON is in pretty format.
    $json_data = json_encode(json_decode($json_data, true), JSON_PRETTY_PRINT);

    // Modify the formatting so that adjacent closing and opening curly braces are on the same line.
    // Note: we can add a similar line if we want to do the same for square brackets.
    $json_data = preg_replace('/},\n +{/s', '},{', $json_data);

    $line_number = 1;

    // Coerce a boolean value.
    $line_numbers = !empty($line_numbers);

    // Split into an array of separate lines.
    $json_lines = explode("\n", $json_data);

    // Wrap the individual lines.
    $json_lines = array_map(function($json_line) use ($line_numbers, &$line_number) {
        // Check if this line contains a property name.
        if(preg_match('/^( +"[^"]+"):/', $json_line, $matches)) {
            // Similar result to explode(':', $json_line), but safer since the colon character may exist somewhere else in the line.
            $parts = array($matches[1], substr($json_line, strlen($matches[1]) + 1));

            // Wrap the property in a span, but keep the spaces outside of it.
            $parts[0] = preg_replace('/^( +)/', '$1<span class="json-property">', $parts[0]) . '</span>';

            // We only want to wrap the other part of the string if it's a value, not an opening brace.
            if(strpos($parts[1], '{') === false && strpos($parts[1], '[') === false) {
                // Similarly, wrap the value in a span, but keep the spaces outside of it.
                $parts[1] = preg_replace('/^( +)/', '$1<span class="json-value">', $parts[1]) . '</span>';
            }

            // Re-join the string parts with the colon we stripped out earlier.
            $json_line = implode(':', $parts);
        }

        // Finally, we can wrap the line with a line number div if needed.
        if($line_numbers) {
            $json_line = '<div class="line" data-line-number="' . ($line_number++) . '">' . $json_line . '</div>';
        }

        return $json_line;
    }, $json_lines);

    // Re-join the lines and return the result.
    return implode("\n", $json_lines);
}

您可能需要稍微修改一下它,才能使它精确地格式化为您的首选项,但这对您来说应该更容易处理。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58866749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档