【问题标题】:Pretty-Printing JSON with PHP使用 PHP 打印漂亮的 JSON
【发布时间】:2011-08-28 13:59:36
【问题描述】:

我正在构建一个将 JSON 数据提供给另一个脚本的 PHP 脚本。我的脚本将数据构建到一个大型关联数组中,然后使用json_encode 输出数据。这是一个示例脚本:

$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);

以上代码产生以下输出:

{"a":"apple","b":"banana","c":"catnip"}

如果你有少量数据,这很好,但我更喜欢这些方面的东西:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

有没有一种方法可以在 PHP 中做到这一点而无需丑陋的 hack?好像Facebook 的某个人想通了。

【问题讨论】:

  • 对于 5.4 之前的 PHP,您可以将 upgradephp 中的 fallback 用作 up_json_encode($data, JSON_PRETTY_PRINT);
  • 使用 header('Content-Type: application/json'); 使浏览器打印漂亮
  • 截至 2018 年 7 月,只需发送 Content-Type: application/json 标头,Firefox 将使用其自己的内部 JSON 解析器显示结果,而 Chrome 显示纯文本。 +1 火狐!

标签: php json pretty-print


【解决方案1】:

PHP 5.4 提供了JSON_PRETTY_PRINT 选项以与json_encode() 调用一起使用。

http://php.net/manual/en/function.json-encode.php

<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);

【讨论】:

  • 谢谢,这是现在最好的方法。当我问这个问题时,我没有 php 5.4...
  • 这里是5.5.3,似乎只是在字符之间添加了一点间距,而不是任何实际的缩进。
  • JSON 不应该包含 HTML 换行符,而换行符在 JSON 中有效。如果您想在网页上显示 JSON,请自己对换行符进行字符串替换,或者将 JSON 放入
    ...
    元素中。语法参考见json.org
  • 如果您希望浏览器很好地显示打印出来的 JSON,请不要忘记将响应 Content-Type 设置为 application/json
  • @countfloortiles 它不能直接工作你需要将你的输出包含在&lt;pre&gt; 标签中,比如&lt;?php ... $json_string = json_encode($data, JSON_PRETTY_PRINT); echo "&lt;pre&gt;".$json_string."&lt;pre&gt;";
【解决方案2】:

此函数将采用 JSON 字符串并将其缩进非常易读。它也应该是收敛的,

prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

输入

{"key1":[1,2,3],"key2":"value"}

输出

{
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"
}

代码

function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}

【讨论】:

    【解决方案3】:

    很多用户建议你使用

    echo json_encode($results, JSON_PRETTY_PRINT);
    

    这是绝对正确的。但这还不够,浏览器需要了解数据的类型,您可以在将数据回显给用户之前指定标头。

    header('Content-Type: application/json');
    

    这将产生格式良好的输出。

    或者,如果你喜欢扩展,你可以使用 JSONView for Chrome。

    【讨论】:

    • 只设置标题,Firefox 会使用自己的内部 JSON 调试解析器完美显示,根本不需要接触 JSON 内容!谢谢!!
    • 谢谢你的帮助。
    • 使用带有 JSON prettifier 扩展的 chromium 浏览器,我的 JSON 输出没有被格式化。 只需设置标题即可使扩展工作。
    • 这很漂亮。谢谢。
    【解决方案4】:

    我意识到这个问题是在询问如何将关联数组编码为格式良好的 JSON 字符串,因此这并不能直接回答问题,但如果您有一个已经是 JSON 格式的字符串,您可以制作它非常简单,只需对其进行解码和重新编码(需要 PHP >= 5.4):

    $json = json_encode(json_decode($json), JSON_PRETTY_PRINT);
    

    示例:

    header('Content-Type: application/json');
    $json_ugly = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    $json_pretty = json_encode(json_decode($json_ugly), JSON_PRETTY_PRINT);
    echo $json_pretty;
    

    这个输出:

    {
        "a": 1,
        "b": 2,
        "c": 3,
        "d": 4,
        "e": 5
    }
    

    【讨论】:

    • 谢谢,它只有在我将这个添加到 php 块的顶部时才有效... header('Content-Type: application/json');
    • @DeyaEldeen 如果您不使用该标头,PHP 将告诉浏览器它正在发送 HTML,因此您必须查看页面源代码才能看到格式化的 JSON 字符串。我以为这被理解了,但我想不是。我已将其添加到我的答案中。
    • 任何在 unix/linux shell 中跟踪/查看日志/文件的人,这就是这里的解决方案!很好看,@Mike,让它易于阅读!。
    • @fusion27 我不太确定你指的是什么日志文件。我从未听说过任何用 JSON 记录任何内容的程序。
    • @Mike,这是一个快速n-dirty PHP我掀起了附加请求正文(这是一个序列化的JSON字符串)发布到我的PHP到一个文本文件中,然后我在unix中尾随它shell,这样我就可以观看实时帖子。我正在使用你的技巧来格式化 JSON,使文本文件更有用。
    【解决方案5】:

    我遇到了同样的问题。

    反正我这里只是用了json格式化代码:

    http://recursive-design.com/blog/2008/03/11/format-json-with-php/

    非常适合我需要它。

    还有一个维护更完善的版本:https://github.com/GerHobbelt/nicejson-php

    【讨论】:

    【解决方案6】:

    将多个答案结合在一起满足我对现有 json 的需求:

    Code:
    echo "<pre>"; 
    echo json_encode(json_decode($json_response), JSON_PRETTY_PRINT); 
    echo "</pre>";
    
    Output:
    {
        "data": {
            "token_type": "bearer",
            "expires_in": 3628799,
            "scopes": "full_access",
            "created_at": 1540504324
        },
        "errors": [],
        "pagination": {},
        "token_type": "bearer",
        "expires_in": 3628799,
        "scopes": "full_access",
        "created_at": 1540504324
    }
    

    【讨论】:

    • 这里有一个小包装函数来做到这一点:function json_print($json) { return '&lt;pre&gt;' . json_encode(json_decode($json), JSON_PRETTY_PRINT) . '&lt;/pre&gt;'; }
    【解决方案7】:

    我用过这个:

    echo "<pre>".json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."</pre>";
    

    或者使用php头文件如下:

    header('Content-type: application/json; charset=UTF-8');
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    

    【讨论】:

      【解决方案8】:

      我从 Composer 获取代码:https://github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.php 和 nicejson:https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.php Composer 代码很好,因为它可以流畅地从 5.3 更新到 5.4,但它只编码对象,而 nicejson 接受 json 字符串,所以我合并了它们。该代码可用于格式化 json 字符串和/或编码对象,我目前在 Drupal 模块中使用它。

      if (!defined('JSON_UNESCAPED_SLASHES'))
          define('JSON_UNESCAPED_SLASHES', 64);
      if (!defined('JSON_PRETTY_PRINT'))
          define('JSON_PRETTY_PRINT', 128);
      if (!defined('JSON_UNESCAPED_UNICODE'))
          define('JSON_UNESCAPED_UNICODE', 256);
      
      function _json_encode($data, $options = 448)
      {
          if (version_compare(PHP_VERSION, '5.4', '>='))
          {
              return json_encode($data, $options);
          }
      
          return _json_format(json_encode($data), $options);
      }
      
      function _pretty_print_json($json)
      {
          return _json_format($json, JSON_PRETTY_PRINT);
      }
      
      function _json_format($json, $options = 448)
      {
          $prettyPrint = (bool) ($options & JSON_PRETTY_PRINT);
          $unescapeUnicode = (bool) ($options & JSON_UNESCAPED_UNICODE);
          $unescapeSlashes = (bool) ($options & JSON_UNESCAPED_SLASHES);
      
          if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes)
          {
              return $json;
          }
      
          $result = '';
          $pos = 0;
          $strLen = strlen($json);
          $indentStr = ' ';
          $newLine = "\n";
          $outOfQuotes = true;
          $buffer = '';
          $noescape = true;
      
          for ($i = 0; $i < $strLen; $i++)
          {
              // Grab the next character in the string
              $char = substr($json, $i, 1);
      
              // Are we inside a quoted string?
              if ('"' === $char && $noescape)
              {
                  $outOfQuotes = !$outOfQuotes;
              }
      
              if (!$outOfQuotes)
              {
                  $buffer .= $char;
                  $noescape = '\\' === $char ? !$noescape : true;
                  continue;
              }
              elseif ('' !== $buffer)
              {
                  if ($unescapeSlashes)
                  {
                      $buffer = str_replace('\\/', '/', $buffer);
                  }
      
                  if ($unescapeUnicode && function_exists('mb_convert_encoding'))
                  {
                      // http://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
                      $buffer = preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
                          function ($match)
                          {
                              return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
                          }, $buffer);
                  } 
      
                  $result .= $buffer . $char;
                  $buffer = '';
                  continue;
              }
              elseif(false !== strpos(" \t\r\n", $char))
              {
                  continue;
              }
      
              if (':' === $char)
              {
                  // Add a space after the : character
                  $char .= ' ';
              }
              elseif (('}' === $char || ']' === $char))
              {
                  $pos--;
                  $prevChar = substr($json, $i - 1, 1);
      
                  if ('{' !== $prevChar && '[' !== $prevChar)
                  {
                      // If this character is the end of an element,
                      // output a new line and indent the next line
                      $result .= $newLine;
                      for ($j = 0; $j < $pos; $j++)
                      {
                          $result .= $indentStr;
                      }
                  }
                  else
                  {
                      // Collapse empty {} and []
                      $result = rtrim($result) . "\n\n" . $indentStr;
                  }
              }
      
              $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)
              {
                  $result .= $newLine;
      
                  if ('{' === $char || '[' === $char)
                  {
                      $pos++;
                  }
      
                  for ($j = 0; $j < $pos; $j++)
                  {
                      $result .= $indentStr;
                  }
              }
          }
          // If buffer not empty after formating we have an unclosed quote
          if (strlen($buffer) > 0)
          {
              //json is incorrectly formatted
              $result = false;
          }
      
          return $result;
      }
      

      【讨论】:

      【解决方案9】:

      如果您使用的是 Firefox,请安装 JSONovich。我知道这不是一个真正的 PHP 解决方案,但它可以用于开发目的/调试。

      【讨论】:

      • 我认为这是开发 api 时的正确解决方案。它提供了两全其美,易于调试,因为您可以阅读所有内容并且您不会改变后端行为,包括其性能。
      • 同意,它的格式很好,颜色也可以折叠。比你希望用一点 PHP 实现的要好得多
      【解决方案10】:

      彩色全输出:Tiny Solution

      代码:

      $s = '{"access": {"token": {"issued_at": "2008-08-16T14:10:31.309353", "expires": "2008-08-17T14:10:31Z", "id": "MIICQgYJKoZIhvcIegeyJpc3N1ZWRfYXQiOiAi"}, "serviceCatalog": [], "user": {"username": "ajay", "roles_links": [], "id": "16452ca89", "roles": [], "name": "ajay"}}}';
      
      $crl = 0;
      $ss = false;
      echo "<pre>";
      for($c=0; $c<strlen($s); $c++)
      {
          if ( $s[$c] == '}' || $s[$c] == ']' )
          {
              $crl--;
              echo "\n";
              echo str_repeat(' ', ($crl*2));
          }
          if ( $s[$c] == '"' && ($s[$c-1] == ',' || $s[$c-2] == ',') )
          {
              echo "\n";
              echo str_repeat(' ', ($crl*2));
          }
          if ( $s[$c] == '"' && !$ss )
          {
              if ( $s[$c-1] == ':' || $s[$c-2] == ':' )
                  echo '<span style="color:#0000ff;">';
              else
                  echo '<span style="color:#ff0000;">';
          }
          echo $s[$c];
          if ( $s[$c] == '"' && $ss )
              echo '</span>';
          if ( $s[$c] == '"' )
                $ss = !$ss;
          if ( $s[$c] == '{' || $s[$c] == '[' )
          {
              $crl++;
              echo "\n";
              echo str_repeat(' ', ($crl*2));
          }
      }
      echo $s[$c];
      

      【讨论】:

      • 这很有帮助,尽管其中有一些错误。我修复了它们,现在它就像一个魅力,功能一点也不大!谢谢阿杰
      • 如果有人想使用它,只是对修复发表评论...在第二个和第三个 if 条件中添加验证检查 $c > 1,最后一个 echo 将其包装成 is_array( $s) 如果。这应该涵盖它,你不应该得到任何未初始化的字符串偏移错误。
      【解决方案11】:

      php>5.4 的简单方法:就像在 Facebook 图表中一样

      $Data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
      $json= json_encode($Data, JSON_PRETTY_PRINT);
      header('Content-Type: application/json');
      print_r($json);
      

      浏览器中的结果

      {
          "a": "apple",
          "b": "banana",
          "c": "catnip"
      }
      

      【讨论】:

      • @Madbreaks,在php文件中打印效果很好,不需要写在json文件中,和facebook一样。
      【解决方案12】:

      格式化 JSON 数据的最佳方式是这样的!

      header('Content-type: application/json; charset=UTF-8');
      echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
      

      将 $response 替换为您需要转换为 JSON 的数据

      【讨论】:

        【解决方案13】:

        &lt;pre&gt;json_encode()JSON_PRETTY_PRINT 选项结合使用:

        <pre>
            <?php
            echo json_encode($dataArray, JSON_PRETTY_PRINT);
            ?>
        </pre>
        

        【讨论】:

          【解决方案14】:

          如果您有现有的 JSON ($ugly_json)

          echo nl2br(str_replace(' ', '&nbsp;', (json_encode(json_decode($ugly_json), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))));
          

          【讨论】:

          • 请在您的答案中添加一些解释,以便其他人可以从中学习
          【解决方案15】:

          更简单,输入 128 - 是“JSON_PRETTY_PRINT”的同义词

          json_encode($json,128);
          //OR same
          json_encode($json,JSON_PRETTY_PRINT );
          

          【讨论】:

          • 请分享更多细节。对我来说,这看起来像是 awie29urh2 九年前提供的答案的副本。有什么新的东西你想强调吗?
          【解决方案16】:

          您可以在 switch 语句中稍微修改 Kendall Hopkins 的答案,通过将 json 字符串传递到以下内容来获得外观漂亮且缩进良好的打印输出:

          function prettyPrint( $json ){
          
          $result = '';
          $level = 0;
          $in_quotes = false;
          $in_escape = false;
          $ends_line_level = NULL;
          $json_length = strlen( $json );
          
          for( $i = 0; $i < $json_length; $i++ ) {
              $char = $json[$i];
              $new_line_level = NULL;
              $post = "";
              if( $ends_line_level !== NULL ) {
                  $new_line_level = $ends_line_level;
                  $ends_line_level = NULL;
              }
              if ( $in_escape ) {
                  $in_escape = false;
              } else if( $char === '"' ) {
                  $in_quotes = !$in_quotes;
              } else if( ! $in_quotes ) {
                  switch( $char ) {
                      case '}': case ']':
                          $level--;
                          $ends_line_level = NULL;
                          $new_line_level = $level;
                          $char.="<br>";
                          for($index=0;$index<$level-1;$index++){$char.="-----";}
                          break;
          
                      case '{': case '[':
                          $level++;
                          $char.="<br>";
                          for($index=0;$index<$level;$index++){$char.="-----";}
                          break;
                      case ',':
                          $ends_line_level = $level;
                          $char.="<br>";
                          for($index=0;$index<$level;$index++){$char.="-----";}
                          break;
          
                      case ':':
                          $post = " ";
                          break;
          
                      case "\t": case "\n": case "\r":
                          $char = "";
                          $ends_line_level = $new_line_level;
                          $new_line_level = NULL;
                          break;
                  }
              } else if ( $char === '\\' ) {
                  $in_escape = true;
              }
              if( $new_line_level !== NULL ) {
                  $result .= "\n".str_repeat( "\t", $new_line_level );
              }
              $result .= $char.$post;
          }
          
          echo "RESULTS ARE: <br><br>$result";
          return $result;
          

          }

          现在只需运行函数 prettyPrint( $your_json_string );内联在您的 php 中并享受打印输出。如果你是一个极简主义者并且由于某种原因不喜欢括号,你可以通过在 $char 的前三个 switch 案例中将 $char.="&lt;br&gt;"; 替换为 $char="&lt;br&gt;"; 来轻松摆脱括号。这是卡尔加里市的 google maps API 调用所获得的结果

          RESULTS ARE: 
          
          {
          - - - "results" : [
          - - -- - - {
          - - -- - -- - - "address_components" : [
          - - -- - -- - -- - - {
          - - -- - -- - -- - -- - - "long_name" : "Calgary"
          - - -- - -- - -- - -- - - "short_name" : "Calgary"
          - - -- - -- - -- - -- - - "types" : [
          - - -- - -- - -- - -- - -- - - "locality"
          - - -- - -- - -- - -- - -- - - "political" ]
          - - -- - -- - -- - - }
          - - -- - -- - -
          - - -- - -- - -- - - {
          - - -- - -- - -- - -- - - "long_name" : "Division No. 6"
          - - -- - -- - -- - -- - - "short_name" : "Division No. 6"
          - - -- - -- - -- - -- - - "types" : [
          - - -- - -- - -- - -- - -- - - "administrative_area_level_2"
          - - -- - -- - -- - -- - -- - - "political" ]
          - - -- - -- - -- - - }
          - - -- - -- - -
          - - -- - -- - -- - - {
          - - -- - -- - -- - -- - - "long_name" : "Alberta"
          - - -- - -- - -- - -- - - "short_name" : "AB"
          - - -- - -- - -- - -- - - "types" : [
          - - -- - -- - -- - -- - -- - - "administrative_area_level_1"
          - - -- - -- - -- - -- - -- - - "political" ]
          - - -- - -- - -- - - }
          - - -- - -- - -
          - - -- - -- - -- - - {
          - - -- - -- - -- - -- - - "long_name" : "Canada"
          - - -- - -- - -- - -- - - "short_name" : "CA"
          - - -- - -- - -- - -- - - "types" : [
          - - -- - -- - -- - -- - -- - - "country"
          - - -- - -- - -- - -- - -- - - "political" ]
          - - -- - -- - -- - - }
          - - -- - -- - - ]
          - - -- - -
          - - -- - -- - - "formatted_address" : "Calgary, AB, Canada"
          - - -- - -- - - "geometry" : {
          - - -- - -- - -- - - "bounds" : {
          - - -- - -- - -- - -- - - "northeast" : {
          - - -- - -- - -- - -- - -- - - "lat" : 51.18383
          - - -- - -- - -- - -- - -- - - "lng" : -113.8769511 }
          - - -- - -- - -- - -
          - - -- - -- - -- - -- - - "southwest" : {
          - - -- - -- - -- - -- - -- - - "lat" : 50.84240399999999
          - - -- - -- - -- - -- - -- - - "lng" : -114.27136 }
          - - -- - -- - -- - - }
          - - -- - -- - -
          - - -- - -- - -- - - "location" : {
          - - -- - -- - -- - -- - - "lat" : 51.0486151
          - - -- - -- - -- - -- - - "lng" : -114.0708459 }
          - - -- - -- - -
          - - -- - -- - -- - - "location_type" : "APPROXIMATE"
          - - -- - -- - -- - - "viewport" : {
          - - -- - -- - -- - -- - - "northeast" : {
          - - -- - -- - -- - -- - -- - - "lat" : 51.18383
          - - -- - -- - -- - -- - -- - - "lng" : -113.8769511 }
          - - -- - -- - -- - -
          - - -- - -- - -- - -- - - "southwest" : {
          - - -- - -- - -- - -- - -- - - "lat" : 50.84240399999999
          - - -- - -- - -- - -- - -- - - "lng" : -114.27136 }
          - - -- - -- - -- - - }
          - - -- - -- - - }
          - - -- - -
          - - -- - -- - - "place_id" : "ChIJ1T-EnwNwcVMROrZStrE7bSY"
          - - -- - -- - - "types" : [
          - - -- - -- - -- - - "locality"
          - - -- - -- - -- - - "political" ]
          - - -- - - }
          - - - ]
          
          - - - "status" : "OK" }
          

          【讨论】:

          • 这真是太好了,谢谢。我认为要稍微改进的一件事是使用 var:$indent = "-----",然后使用它(而不是在代码中的不同位置使用 "-----")
          【解决方案17】:

          对于 PHP 5.3 或之前版本的用户,您可以尝试以下操作:

          $pretty_json = "<pre>".print_r(json_decode($json), true)."</pre>";
          
          echo $pretty_json;
          
          

          【讨论】:

            【解决方案18】:

            如果您只使用$json_string = json_encode($data, JSON_PRETTY_PRINT);,您将在浏览器中看到类似这样的内容(使用问题中的Facebook link :)):

            但是如果您使用像 JSONView 这样的 chrome 扩展程序(即使没有上面的 PHP 选项),那么您将获得一个更可读性更高的可调试解决方案,您甚至可以像这样轻松折叠/折叠每个 JSON 对象:

            【讨论】:

              【解决方案19】:

              你可以像下面那样做。

              $array = array(
                 "a" => "apple",
                 "b" => "banana",
                 "c" => "catnip"
              );
              
              foreach ($array as $a_key => $a_val) {
                 $json .= "\"{$a_key}\" : \"{$a_val}\",\n";
              }
              
              header('Content-Type: application/json');
              echo "{\n"  .rtrim($json, ",\n") . "\n}";
              

              上面会输出有点像 Facebook。

              {
              "a" : "apple",
              "b" : "banana",
              "c" : "catnip"
              }
              

              【讨论】:

              • 如果a_val是一个数组还是一个对象呢?
              • 我在问题中使用 Json 回答了一个示例,我会尽快更新我的答案。
              【解决方案20】:

              递归解决方案的经典案例。这是我的:

              class JsonFormatter {
                  public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
                      $inString = $escaped = false;
                      $result = $indent;
              
                      if(is_string($j)) {
                          $bak = $j;
                          $j = str_split(trim($j, '"'));
                      }
              
                      while(count($j)) {
                          $c = array_shift($j);
                          if(false !== strpos("{[,]}", $c)) {
                              if($inString) {
                                  $result .= $c;
                              } else if($c == '{' || $c == '[') {
                                  $result .= $c."\n";
                                  $result .= self::prettyPrint($j, $indentor, $indentor.$indent);
                                  $result .= $indent.array_shift($j);
                              } else if($c == '}' || $c == ']') {
                                  array_unshift($j, $c);
                                  $result .= "\n";
                                  return $result;
                              } else {
                                  $result .= $c."\n".$indent;
                              } 
                          } else {
                              $result .= $c;
                              $c == '"' && !$escaped && $inString = !$inString;
                              $escaped = $c == '\\' ? !$escaped : false;
                          }
                      }
              
                      $j = $bak;
                      return $result;
                  }
              }
              

              用法:

              php > require 'JsonFormatter.php';
              php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
              php > print_r($a);
              Array
              (
                  [foo] => 1
                  [bar] => This "is" bar
                  [baz] => Array
                      (
                          [a] => 1
                          [b] => 2
                          [c] => "3"
                      )
              
              )
              php > echo JsonFormatter::prettyPrint(json_encode($a));
              {
                  "foo":1,
                  "bar":"This \"is\" bar",
                  "baz":{
                      "a":1,
                      "b":2,
                      "c":"\"3\""
                  }
              }
              

              干杯

              【讨论】:

                【解决方案21】:

                这个解决方案让 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(['<', '>', '&'], ['&lt;', '&gt;', '&amp;'], $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);
                }
                

                }

                【讨论】:

                  【解决方案22】:

                  用于 PHP 的 print_r 漂亮打印

                  Example PHP

                  function print_nice($elem,$max_level=10,$print_nice_stack=array()){
                      if(is_array($elem) || is_object($elem)){
                          if(in_array($elem,$print_nice_stack,true)){
                              echo "<font color=red>RECURSION</font>";
                              return;
                          }
                          $print_nice_stack[]=&$elem;
                          if($max_level<1){
                              echo "<font color=red>nivel maximo alcanzado</font>";
                              return;
                          }
                          $max_level--;
                          echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
                          if(is_array($elem)){
                              echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
                          }else{
                              echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
                              echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
                          }
                          $color=0;
                          foreach($elem as $k => $v){
                              if($max_level%2){
                                  $rgb=($color++%2)?"#888888":"#BBBBBB";
                              }else{
                                  $rgb=($color++%2)?"#8888BB":"#BBBBFF";
                              }
                              echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
                              echo '<strong>'.$k."</strong></td><td>";
                              print_nice($v,$max_level,$print_nice_stack);
                              echo "</td></tr>";
                          }
                          echo "</table>";
                          return;
                      }
                      if($elem === null){
                          echo "<font color=green>NULL</font>";
                      }elseif($elem === 0){
                          echo "0";
                      }elseif($elem === true){
                          echo "<font color=green>TRUE</font>";
                      }elseif($elem === false){
                          echo "<font color=green>FALSE</font>";
                      }elseif($elem === ""){
                          echo "<font color=green>EMPTY STRING</font>";
                      }else{
                          echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
                      }
                  }
                  

                  【讨论】:

                    【解决方案23】:

                    1 - json_encode($rows,JSON_PRETTY_PRINT); 返回带有换行符的美化数据。这对命令行输入很有帮助,但正如您所发现的那样,在浏览器中看起来并不那么漂亮。浏览器将接受换行符作为源(因此,查看页面源确实会显示漂亮的 JSON),但它们不用于格式化浏览器中的输出。浏览器需要 HTML。

                    2 - 使用这个函数github

                    <?php
                        /**
                         * Formats a JSON string for pretty printing
                         *
                         * @param string $json The JSON to make pretty
                         * @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks
                         * @return string The prettified output
                         * @author Jay Roberts
                         */
                        function _format_json($json, $html = false) {
                            $tabcount = 0;
                            $result = '';
                            $inquote = false;
                            $ignorenext = false;
                            if ($html) {
                                $tab = "&nbsp;&nbsp;&nbsp;&nbsp;";
                                $newline = "<br/>";
                            } else {
                                $tab = "\t";
                                $newline = "\n";
                            }
                            for($i = 0; $i < strlen($json); $i++) {
                                $char = $json[$i];
                                if ($ignorenext) {
                                    $result .= $char;
                                    $ignorenext = false;
                                } else {
                                    switch($char) {
                                        case '[':
                                        case '{':
                                            $tabcount++;
                                            $result .= $char . $newline . str_repeat($tab, $tabcount);
                                            break;
                                        case ']':
                                        case '}':
                                            $tabcount--;
                                            $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
                                            break;
                                        case ',':
                                            $result .= $char . $newline . str_repeat($tab, $tabcount);
                                            break;
                                        case '"':
                                            $inquote = !$inquote;
                                            $result .= $char;
                                            break;
                                        case '\\':
                                            if ($inquote) $ignorenext = true;
                                            $result .= $char;
                                            break;
                                        default:
                                            $result .= $char;
                                    }
                                }
                            }
                            return $result;
                        }
                    

                    【讨论】:

                      【解决方案24】:

                      这是我自己使用的函数,api 就像 json_encode,除了它有第三个参数 exclude_flags 以防你想排除一些默认标志(如 JSON_UNESCAPED_SLASHES)

                      function json_encode_pretty($data, int $extra_flags = 0, int $exclude_flags = 0): string
                      {
                          // prettiest flags for: 7.3.9
                          $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (defined("JSON_UNESCAPED_LINE_TERMINATORS") ? JSON_UNESCAPED_LINE_TERMINATORS : 0) | JSON_PRESERVE_ZERO_FRACTION | (defined("JSON_THROW_ON_ERROR") ? JSON_THROW_ON_ERROR : 0);
                          $flags = ($flags | $extra_flags) & ~ $exclude_flags;
                          return (json_encode($data, $flags));
                      }
                      

                      【讨论】:

                        【解决方案25】:

                        以下对我有用:

                        test.php 的内容:

                        <html>
                        <body>
                        Testing JSON array output
                          <pre>
                          <?php
                          $data = array('a'=>'apple', 'b'=>'banana', 'c'=>'catnip');
                          // encode in json format 
                          $data = json_encode($data);
                        
                          // json as single line
                          echo "</br>Json as single line </br>";
                          echo $data;
                          // json as an array, formatted nicely
                          echo "</br>Json as multiline array </br>";
                          print_r(json_decode($data, true));
                          ?>
                          </pre>
                        </body>
                        </html>
                        

                        输出:

                        Testing JSON array output
                        
                        
                        Json as single line 
                        {"a":"apple","b":"banana","c":"catnip"}
                        Json as multiline array 
                        Array
                        (
                            [a] => apple
                            [b] => banana
                            [c] => catnip
                        )
                        

                        还要注意在 html 中使用“pre”标签。

                        希望对某人有所帮助

                        【讨论】:

                        • 这不能回答问题。您正在转储变量,而不是打印格式化的 JSON。
                        【解决方案26】:

                        如果您正在使用 MVC

                        尝试在您的控制器中执行此操作

                        public function getLatestUsers() {
                            header('Content-Type: application/json');
                            echo $this->model->getLatestUsers(); // this returns json_encode($somedata, JSON_PRETTY_PRINT)
                        }
                        

                        然后,如果您调用 /getLatestUsers,您将获得漂亮的 JSON 输出;)

                        【讨论】:

                        • 在打印结束的回声后查看我的评论
                        • MVC是一种框架设计,与输出JSON无关。
                        • 这是 2013 人的回答 ;)
                        猜你喜欢
                        • 2014-05-19
                        • 2015-07-03
                        • 2015-08-26
                        相关资源
                        最近更新 更多