Search code examples
phpjsonpretty-print

How can I customise Pretty_Printed JSON in PHP 7.x?


PHP's built-in PRETTY_PRINT doesn't allow for much customisation beyond a few additional flags:

  • JSON_UNESCAPED_SLASHES
  • JSON_UNESCAPED_UNICODE

But the kind of customisation I am looking for is one that transforms the displayed JSON, so that it ends up looking:

  • less horizontal
    • 2-space indents instead of 4
  • more vertical
    • newlines at the start of arrays & objects
    • newlines between same-level arrays & objects
    • newlines between same-level entries

So instead of the horizontally spaced out:

[
    {
        "berry": "banana",
        "description": [
            "yellow",
            "sweet"
        ],
        "notes": []
      },
      {
        "berry": "aubergine",
        "taste": [
            "purple",
            "bitter"
        ],
        "notes": []
      }
]

I can have the vertically spaced out:

[
  {
    "berry": "banana",

    "description": [

      "yellow",
      "sweet"
    ],

    "notes": []
  },


  {
    "berry": "aubergine",

    "description": [

      "purple",
      "bitter"
    ],

    "notes": []
  }
]

Is there anything in PHP 7.x which would enable me to customise the output of pretty-printed JSON?


Historical Note:

The classic reference to reformatting JSON in PHP is Format JSON With PHP by Dave Perrett.

This dates from 2008, pre-dating even the PRETTY_PRINT flag (which arrived 4 years later in 2012).


Solution

  • I can't find any specific additions to pretty printing JSON in PHP 7.x, but it strikes me that I can:

    • use the PRETTY_PRINT flag
    • then follow up with a series of str_replace() and preg_replace() to achieve my customised output (as outlined in the question at the top)

    Example:

    function Custom_Pretty_Print_JSON($Data) {
    
      if (!is_null(json_decode($Data, TRUE))) {
    
        $Data = json_decode($Data, TRUE);
      }
    
      $String = json_encode($Data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    
      $String = str_replace('    ', '  ', $String);
    
      $String = preg_replace("/(\:\s\{|\:\s\[|\,)\n([\s]+)(\"|\{|\[)/", "$1\n\n$2$3", $String);
    
      return $String;
    }