繁体   English   中英

需要帮助使用 JSON 对这个逻辑进行排序

[英]Need help sorting this logic with JSON Pretty Print

尝试漂亮地打印 json,并且工作正常,概念,似乎在打印每个 object 数组之间的对象数组时添加了额外的一行。 可以在这个逻辑上使用一些帮助,因为我有一段时间没有触及这个......

漂亮打印的代码如下:

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

这是一个图像,如果可能的话,想去掉数组对象之间的额外空间。 这里的任何帮助,将不胜感激。

json漂亮的打印输出

你为什么要手动解析 JSON? 该代码将非常难以推理和维护,尤其是当您稍后在几乎不可避免地出现错误时返回它时。

与其采取困难的方法,不如考虑执行以下操作:
1. 重新格式化 JSON 使其适合您的需要。 例如,在这种情况下,您更愿意将对象的右括号和结束括号保持在同一行,而不是在不同的行上。
2. 将已经格式化的 JSON 拆分为单独的行。
3. 将 JSON 的各行包裹在 HTML 中。
4. 重新加入线以获得最终的 HTML。

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);
}

您可能需要稍微修改一下以使其格式完全符合您的喜好,但这对您来说应该更容易使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM