使用 PHP 打印漂亮的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6054033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pretty-Printing JSON with PHP
提问by Zach Rattner
I'm building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode
. Here is an example script:
我正在构建一个将 JSON 数据提供给另一个脚本的 PHP 脚本。我的脚本将数据构建到一个大型关联数组中,然后使用json_encode
. 这是一个示例脚本:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
The above code yields the following output:
上面的代码产生以下输出:
{"a":"apple","b":"banana","c":"catnip"}
This is great if you have a small amount of data, but I'd prefer something along these lines:
如果您有少量数据,这很好,但我更喜欢以下方面的内容:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebookfigured it out.
有没有办法在没有丑陋黑客的情况下在 PHP 中做到这一点?似乎Facebook 的某个人发现了这一点。
回答by ekillaby
PHP 5.4 offers the JSON_PRETTY_PRINT
option for use with the json_encode()
call.
PHP 5.4 提供了JSON_PRETTY_PRINT
与json_encode()
调用一起使用的选项。
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-encode.php
<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);
回答by Kendall Hopkins
This function will take JSON string and indent it very readable. It also should be convergent,
此函数将采用 JSON 字符串并将其缩进,可读性很强。也应该收敛,
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
Input
输入
{"key1":[1,2,3],"key2":"value"}
Output
输出
{
"key1": [
1,
2,
3
],
"key2": "value"
}
Code
代码
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;
}
回答by Wahib Zakraoui
Many users suggested that you use
许多用户建议您使用
echo json_encode($results, JSON_PRETTY_PRINT);
Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.
这是绝对正确的。但这还不够,浏览器需要了解数据的类型,您可以在将数据回显给用户之前指定标题。
header('Content-Type: application/json');
This will result in a well formatted output.
这将导致格式良好的输出。
Or, if you like extensions you can use JSONView for Chrome.
或者,如果你喜欢扩展,你可以使用 JSONView for Chrome。
回答by Jason
I had the same issue.
我遇到过同样的问题。
Anyway I just used the json formatting code here:
无论如何,我只是在这里使用了 json 格式代码:
http://recursive-design.com/blog/2008/03/11/format-json-with-php/
http://recursive-design.com/blog/2008/03/11/format-json-with-php/
Works well for what I needed it for.
非常适合我需要它的用途。
And a more maintained version: https://github.com/GerHobbelt/nicejson-php
还有一个更维护的版本:https: //github.com/GerHobbelt/nicejson-php
回答by Mike
I realize this question is asking about how to encode an associative array to a pretty-formatted JSON string, so this doesn't directly answer the question, but if you have a string that is already in JSON format, you can make it pretty simply by decoding and re-encoding it (requires PHP >= 5.4):
我意识到这个问题是问如何将关联数组编码为格式漂亮的 JSON 字符串,因此这不能直接回答问题,但是如果您有一个已经是 JSON 格式的字符串,则可以非常简单通过解码和重新编码(需要 PHP >= 5.4):
$json = json_encode(json_decode($json), JSON_PRETTY_PRINT);
Example:
例子:
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;
This outputs:
这输出:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
回答by Kevin
Gluing several answers together fit my need for existing json:
将几个答案粘合在一起符合我对现有 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
}
回答by ulk200
I took the code from Composer : https://github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.phpand nicejson : https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.phpComposer code is good because it updates fluently from 5.3 to 5.4 but it only encodes object whereas nicejson takes json strings, so i merged them. The code can be used to format json string and/or encode objects, i'm currently using it in a Drupal module.
我从 Composer 获取了代码:https: //github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.php和 nicejson:https: //github.com/GerHobbelt/nicejson-php/blob /master/nicejson.phpComposer 代码很好,因为它可以从 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;
}
回答by Jay Sidri
回答by Safeer Ahmed
I have used this:
我用过这个:
echo "<pre>".json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."</pre>";
Or use php headers as below:
或者使用 php 头文件如下:
header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
回答by dknepa
Simple way for php>5.4: like in Facebook graph
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);
Result in browser
浏览器中的结果
{
"a": "apple",
"b": "banana",
"c": "catnip"
}