我正在构建一个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的某个人发现了这一点。
以下是对我有效的方法:
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的需求:
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
}
有颜色全输出:微小的解决方案
代码:
$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];
我意识到这个问题是问如何编码一个关联数组到一个漂亮的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
}