Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty-Printing JSON with PHP

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.

like image 630
Zach Rattner Avatar asked May 19 '11 05:05

Zach Rattner


People also ask

How do I print JSON data in pretty format?

We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.

How do I pretty print a JSON string?

JSON. stringify(obj, null, '\t'); This "pretty-prints" your JSON string, using a tab for indentation. Save this answer.

Can JSON be used with PHP?

PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode()


1 Answers

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); 
like image 195
awhie29urh2 Avatar answered Sep 21 '22 09:09

awhie29urh2