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
. Here is an example script:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
The above code yields the following output:
{"a":"apple","b":"banana","c":"catnip"}
This is great if you have a small amount of data, but I'd prefer something along these lines:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.
Use
<pre>
in combination withjson_encode()
and theJSON_PRETTY_PRINT
option:You can modify Kendall Hopkins' answer a little in the switch statement to get a pretty clean looking and nicely indented printout by passing a json string into the following:
}
Now just run the function prettyPrint( $your_json_string ); inline in your php and enjoy the printout. If you're a minimalist and don't like brackets for some reason, you can get rid of those easily by replacing the
$char.="<br>";
with$char="<br>";
in the top three switch cases on $char. Here's what you get for a google maps API call for the city of CalgaryClassic case for a recursive solution. Here's mine:
Usage:
Cheers
You could do it like below.
Above would output kind of like Facebook.
I took the code from Composer : https://github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.php and nicejson : https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.php Composer code is good because it updates fluently from 5.3 to 5.4 but it only encodes object whereas nicejson takes json strings, so i merged them. The code can be used to format json string and/or encode objects, i'm currently using it in a Drupal module.
If you used only
$json_string = json_encode($data, JSON_PRETTY_PRINT);
, you will get in the browser something like this (using the Facebook link from the question :) ):but if you used a chrome Extension like JSONView (even without the PHP option above), then you get a more pretty readable debuggable solution where you can even Fold/Collapse each single JSON object easily like this: