4

I would like to format the echo json_encode, the output is currently

{"results":{"course":"CC140","books":{"book":[[{"id":"300862","title":"Building object-oriented software","isbn":"0070431965","borrowedcount":"6"}]]}}}

Whereas i would like to to output like this:

{
    "results": {
        "course": "CC140",
        "books": {
            "book": [
                [
                    {
                        "id": "300862",
                        "title": "Building object-oriented software",
                        "isbn": "0070431965",
                        "borrowedcount": "6"
                    }
                ]
            ]
        }
    }
}

This is the code that makes the JSON

$temp = array();
    foreach ($my_array as $counter => $bc) {
        $temp['id'] = "$id[$counter]";
        $temp['title'] = "$title[$counter]";
        $temp['isbn'] = "$isbn[$counter]";
        $temp['borrowedcount'] = "$borrowedcount[$counter]";
        $t2[] = $temp;
    }

        $data = array(
  "results" => array(
    "course" => "$cc",
    "books" => array(
      "book" =>
      array(  
        $t2
      )
    )
  )
);
    echo json_encode($data);

Any help or pointers would be appreciated, thanks

Adding this

header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);

formats the JSON, but the header also outs the entire HTML document

Craig Weston
  • 141
  • 2
  • 4
  • 10

2 Answers2

19

The first piece of advice I'd give is: Don't. JSON is a data format. Deal with it using tools rather then trying to have your server format it.

If you are going to ignore that, then see the manual for the json_encode function where it gives a list of options which includes JSON_PRETTY_PRINT which is described as Use whitespace in returned data to format it. Available since PHP 5.4.0.

Thus the steps are:

  1. Make sure you are using PHP 5.4.0 or newer
  2. json_encode($data, JSON_PRETTY_PRINT);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 6
    the Pretty Print alone does not out it correctly however adding header('Content-type: application/json'); before works, but outputs the HTML document with it – Craig Weston Feb 25 '13 at 13:03
  • I disagree with your first statement, the fact that JSON is a data format is not a reason to keep it hard to read for humans, as soon as the standard allows such formating, which is the case for JSON. – Harps Nov 18 '21 at 10:44
4

You can use json_encode($data, JSON_PRETTY_PRINT) in php 5.4+

In php 5.3 & under that, you could try formatting it with regular expressions, but it's not too safe (or you could use library for encoding json).

pozs
  • 34,608
  • 5
  • 57
  • 63