某处是否有“简单”脚本可以获取 json 数据并对其进行格式化以使其更具可读性?
例如:
// $response is a json encoded string.
var_dump($response);
以上将所有内容输出在一行上。我希望它是缩进和间隔的,以便于阅读。
请注意,var_dump
它及其简洁的表亲确实打印换行符。var_export
请记住,默认情况下 HTML 文档中不显示换行符。在 HTML 上下文中,您需要这样:
echo '<div style="font-family: monospace; white-space:pre;">';
echo htmlspecialchars(var_export($response));
echo '</div>';
在 php 5.4+ 中,您可以简单地使用json_encodePRETTY_PRINT
的标志:
echo json_encode($response, JSON_PRETTY_PRINT);
同样,在 HTML 上下文中,您必须如上所述包装它。
将其粘贴到JSONLint.com并单击验证。
有一个类似的问题,因为我将一个序列化的 javascript 对象发布到一个 php 脚本,并希望以人类可读的格式将它保存到服务器。
在 webdeveloper.com 论坛上找到了这篇文章,并稍微调整了代码以适应我自己的感受(它需要一个 json 编码的字符串):
function jsonToReadable($json){
$tc = 0; //tab count
$r = ''; //result
$q = false; //quotes
$t = "\t"; //tab
$nl = "\n"; //new line
for($i=0;$i<strlen($json);$i++){
$c = $json[$i];
if($c=='"' && $json[$i-1]!='\\') $q = !$q;
if($q){
$r .= $c;
continue;
}
switch($c){
case '{':
case '[':
$r .= $c . $nl . str_repeat($t, ++$tc);
break;
case '}':
case ']':
$r .= $nl . str_repeat($t, --$tc) . $c;
break;
case ',':
$r .= $c;
if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);
break;
case ':':
$r .= $c . ' ';
break;
default:
$r .= $c;
}
}
return $r;
}
传入
{"object":{"array":["one","two"],"sub-object":{"one":"string","two":2}}}
返回
{
"object": {
"array": [
"one",
"two"
],
"sub-object": {
"one": "string",
"two": 2
}
}
}
json_encode($response, JSON_PRETTY_PRINT);
现在是 2017 年,我认为这应该是任何使用现代 PHP 版本的人的答案。
请注意,对于如何根据自己的喜好对 JSON 字符串进行编码,存在许多选项。来自php.net:
JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR
echo '<pre>';
print_r(json_decode($response));
echo '</pre>';
太简单?
管它通过python -mjson.tool
。
使用 python 的建议对我来说效果很好。下面是一些从 PHP 中使用它的代码:
function jsonEncode( $data, $pretty = false ) {
$str = json_encode($data);
if( $pretty ) {
$descriptorSpec = array(
0 => array('pipe', 'r'), // stdin is a pipe that the child will read from
1 => array('pipe', 'w'), // stdout is a pipe that the child will write to
);
$fp = proc_open('/usr/bin/python -mjson.tool', $descriptorSpec, $pipes);
fputs($pipes[0], $str);
fclose($pipes[0]);
$str = '';
while( !feof($pipes[1]) ) {
$str .= $chunk = fgets($pipes[1], 1024);
}
fclose($pipes[1]);
}
return $str;
}