Zac*_*ner 550 php json pretty-print
我正在构建一个PHP脚本,将JSON数据提供给另一个脚本.我的脚本将数据构建为一个大的关联数组,然后使用输出数据json_encode.这是一个示例脚本:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
上面的代码产生以下输出:
{"a":"apple","b":"banana","c":"catnip"}
Run Code Online (Sandbox Code Playgroud)
如果您有少量数据,这很好,但我更喜欢这些内容:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在没有丑陋黑客的情况下在PHP中执行此操作?好像Facebook的某个人想出来了.
eki*_*aby 1060
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);
Run Code Online (Sandbox Code Playgroud)
Ken*_*ins 182
这个函数将采用JSON字符串并缩进它非常易读.它也应该是收敛的,
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
Run Code Online (Sandbox Code Playgroud)
输入
{"key1":[1,2,3],"key2":"value"}
Run Code Online (Sandbox Code Playgroud)
产量
{
"key1": [
1,
2,
3
],
"key2": "value"
}
Run Code Online (Sandbox Code Playgroud)
码
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 73
很多用户建议你使用
echo json_encode($results, JSON_PRETTY_PRINT);
Run Code Online (Sandbox Code Playgroud)
哪个是绝对正确的.但这还不够,浏览器需要了解数据类型,您可以在将数据回送给用户之前指定标题.
header('Content-Type: application/json');
Run Code Online (Sandbox Code Playgroud)
这将导致格式良好的输出.
或者,如果您喜欢扩展,则可以使用JSONView for Chrome.
Jas*_*son 40
我遇到过同样的问题.
无论如何我只是在这里使用了json格式代码:
http://recursive-design.com/blog/2008/03/11/format-json-with-php/
适合我需要的东西.
还有一个更加维护的版本:https://github.com/GerHobbelt/nicejson-php
Mik*_*ike 27
我意识到这个问题是关于如何将关联数组编码为漂亮格式的JSON字符串,所以这并没有直接回答这个问题,但如果你有一个已经是JSON格式的字符串,你可以简单地说通过解码和重新编码(需要PHP> = 5.4):
$json = json_encode(json_decode($json), JSON_PRETTY_PRINT);
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
这输出:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
Run Code Online (Sandbox Code Playgroud)
Kev*_*vin 20
将几个答案粘合在一起符合我对现有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
}
Run Code Online (Sandbox Code Playgroud)
Saf*_*med 20
我用过这个:
echo "<pre>".json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."</pre>";
Run Code Online (Sandbox Code Playgroud)
或者使用 php 头文件如下:
header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Run Code Online (Sandbox Code Playgroud)
daz*_*act 12
更容易提醒:输入128
128是常量“JSON_PRETTY_PRINT”的同义词
(PHP 文档网站)
json_encode($json,128);
//similar to
json_encode($json,JSON_PRETTY_PRINT );
Run Code Online (Sandbox Code Playgroud)
ulk*_*200 10
我从Composer中获取代码:https://github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.php和nicejson:https://github.com/GerHobbelt/nicejson-php/blob /master/nicejson.php 编写器代码很好,因为它从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;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
格式化 JSON 数据的最佳方式是这样的!
header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Run Code Online (Sandbox Code Playgroud)
将 $response 替换为您需要转换为 JSON 的数据
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);
Run Code Online (Sandbox Code Playgroud)
结果在浏览器中
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
Run Code Online (Sandbox Code Playgroud)
使用<pre>与组合json_encode()和JSON_PRETTY_PRINT选项:
<pre>
<?php
echo json_encode($dataArray, JSON_PRETTY_PRINT);
?>
</pre>
Run Code Online (Sandbox Code Playgroud)
如果你有现有的JSON($ugly_json)
echo nl2br(str_replace(' ', ' ', (json_encode(json_decode($ugly_json), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))));
Run Code Online (Sandbox Code Playgroud)
我通常使用其中之一。
echo()如果您已有 JSON 字符串,则只需使用和的组合即可print_r()。不要忘记传递print_r()to的第二个参数true,以便它返回值而不是打印它:
echo('<pre>' . print_r($json, true) . '</pre>');
Run Code Online (Sandbox Code Playgroud)
或者您可以使用方便die()的调试:
die('<pre>' . print_r($json, true) . '</pre>');
Run Code Online (Sandbox Code Playgroud)
如果您有数组,则需要先将其转换为 JSON 字符串。json_encode()请务必使用标志设置第二个参数,JSON_PRETTY_PRINT以便正确呈现您的 JSON:
echo('<pre>' . print_r(json_encode($array, JSON_PRETTY_PRINT), true) . '</pre>');
Run Code Online (Sandbox Code Playgroud)
或用于调试:
die('<pre>' . print_r(json_encode($array, JSON_PRETTY_PRINT), true) . '</pre>');
Run Code Online (Sandbox Code Playgroud)
小智 5
全彩输出: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];
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以在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;
Run Code Online (Sandbox Code Playgroud)
}
现在只需运行prettyPrint函数($ your_json_string); 内联你的PHP并享受打印输出.如果你是一个极简主义者并且由于某些原因不喜欢括号,你可以通过替换$ char中前三个开关盒中的$char.="<br>";with $char="<br>";来轻松摆脱它们.以下是您为卡尔加里市进行Google地图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" }
Run Code Online (Sandbox Code Playgroud)
这个解决方案使 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(['<', '>', '&'], ['<', '>', '&'], $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);
}
Run Code Online (Sandbox Code Playgroud)
}
对于那些运行 PHP 5.3 或之前版本的人,您可以尝试以下操作:
$pretty_json = "<pre>".print_r(json_decode($json), true)."</pre>";
echo $pretty_json;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
481105 次 |
| 最近记录: |