I\'m building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode
Classic case for a recursive solution. Here's mine:
class JsonFormatter {
public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
$inString = $escaped = false;
$result = $indent;
if(is_string($j)) {
$bak = $j;
$j = str_split(trim($j, '"'));
}
while(count($j)) {
$c = array_shift($j);
if(false !== strpos("{[,]}", $c)) {
if($inString) {
$result .= $c;
} else if($c == '{' || $c == '[') {
$result .= $c."\n";
$result .= self::prettyPrint($j, $indentor, $indentor.$indent);
$result .= $indent.array_shift($j);
} else if($c == '}' || $c == ']') {
array_unshift($j, $c);
$result .= "\n";
return $result;
} else {
$result .= $c."\n".$indent;
}
} else {
$result .= $c;
$c == '"' && !$escaped && $inString = !$inString;
$escaped = $c == '\\' ? !$escaped : false;
}
}
$j = $bak;
return $result;
}
}
Usage:
php > require 'JsonFormatter.php';
php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
php > print_r($a);
Array
(
[foo] => 1
[bar] => This "is" bar
[baz] => Array
(
[a] => 1
[b] => 2
[c] => "3"
)
)
php > echo JsonFormatter::prettyPrint(json_encode($a));
{
"foo":1,
"bar":"This \"is\" bar",
"baz":{
"a":1,
"b":2,
"c":"\"3\""
}
}
Cheers
Many users suggested that you use
echo json_encode($results, JSON_PRETTY_PRINT);
Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.
header('Content-Type: application/json');
This will result in a well formatted output.
Or, if you like extensions you can use JSONView for Chrome.
Simple way for php>5.4: like in Facebook graph
$Data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
$json= json_encode($Data, JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);
Result in browser
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
This function will take JSON string and indent it very readable. It also should be convergent,
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
Input
{"key1":[1,2,3],"key2":"value"}
Output
{
"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;
}
If you are working with MVC
try doing this in your controller
public function getLatestUsers() {
header('Content-Type: application/json');
echo $this->model->getLatestUsers(); // this returns json_encode($somedata, JSON_PRETTY_PRINT)
}
then if you call /getLatestUsers you will get a pretty JSON output ;)
PHP 5.4 offers the JSON_PRETTY_PRINT
option for use with the json_encode()
call.
http://php.net/manual/en/function.json-encode.php
<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);