We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this questionYou might say this is duplicate of this question, but original question WASN'T answered there. Important part of question is: programmatically
?
Is there any php function? Native or homemade?
json_encode() has a flag JSON_PRETTY_PRINT
echo json_encode($data, JSON_PRETTY_PRINT);
had the same question right now. But as you also i'm having php < 5.4. Zend Framework has Zend_Json::prettyPrint(). Works very well.
I created a non-destructive JSON beautifier that support multiple deep levels.
/**
* JSON beautifier
*
* @param string The original JSON string
* @param string Return string
* @param string Tab string
* @return string
*/
function pretty_json($json, $ret= "\n", $ind="\t") {
$beauty_json = '';
$quote_state = FALSE;
$level = 0;
$json_length = strlen($json);
for ($i = 0; $i < $json_length; $i++)
{
$pre = '';
$suf = '';
switch ($json[$i])
{
case '"':
$quote_state = !$quote_state;
break;
case '[':
$level++;
break;
case ']':
$level--;
$pre = $ret;
$pre .= str_repeat($ind, $level);
break;
case '{':
if ($i - 1 >= 0 && $json[$i - 1] != ',')
{
$pre = $ret;
$pre .= str_repeat($ind, $level);
}
$level++;
$suf = $ret;
$suf .= str_repeat($ind, $level);
break;
case ':':
$suf = ' ';
break;
case ',':
if (!$quote_state)
{
$suf = $ret;
$suf .= str_repeat($ind, $level);
}
break;
case '}':
$level--;
case ']':
$pre = $ret;
$pre .= str_repeat($ind, $level);
break;
}
$beauty_json .= $pre.$json[$i].$suf;
}
return $beauty_json;
}
This simple trick did the job for me, I didn't wanted any additional libraries or functions:
$json = '{"status":"0","status_translated":"Request successful!","data":"1"}';
$json_beautified = str_replace(array("{", "}", '","'), array("{<br /> ", "<br />}", '",<br /> "'), $json);
And the result looks like this:
{
"status":"0",
"status_translated":"Request successful!",
"data":"1"
}
This is only for json code that goes 1 step in depth, I hope it helps.
For command line usage, you can use the js beautifier. No need to share your data with external sites.
https://github.com/vivekpathak/tools/blob/master/jb/jb
精彩评论