我正在构建一个PHP脚本,将JSON数据提供给另一个脚本。我的脚本将数据构建到一个大型关联数组中,然后使用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中做到这一点,而不需要丑陋的黑客?似乎Facebook的某个人发现了这一点。
这个函数将接受JSON字符串并缩进,使其非常可读。它也是收敛的,
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
输入
{"key1":[1,2,3],"key2":"value"}
输出
{
"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;
}
这个解决方案生成“非常漂亮”的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);
}
}
你可以在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.="<br>"来轻松摆脱括号;char美元= " < br > ";在$char上的前三个开关案例中。这是你为卡尔加里市的谷歌地图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" }