Last active
March 5, 2021 15:43
-
-
Save itsjavi/b8b575e21c3bcc768e347c0e5f9ed5f0 to your computer and use it in GitHub Desktop.
PHP json_encode prettify compact mode with indentation level options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Support; | |
class JsonEncoder | |
{ | |
private const JSON_PRETTY_PRINT_INDENT = 4; | |
public function decode($json, int $flags = JSON_THROW_ON_ERROR, int $depth = 512): array | |
{ | |
return json_decode((string)$json, true, $depth, $flags); | |
} | |
public function encode( | |
$value, | |
int $flags = JSON_THROW_ON_ERROR, | |
int $depth = 512, | |
int $indentationDepth = 10, | |
string $indentationReplacement = ' ' | |
): string { | |
$prettify = ($flags & JSON_PRETTY_PRINT) === JSON_PRETTY_PRINT; | |
$json = json_encode($value, $flags, $depth); | |
if (!$prettify || ($indentationDepth === 0)) { | |
return $json; | |
} | |
$indentedSpace = self::JSON_PRETTY_PRINT_INDENT * ($indentationDepth + 1); | |
$leadingIndentedSpace = self::JSON_PRETTY_PRINT_INDENT * $indentationDepth; | |
$json = preg_replace("/\\n^\\s{{$indentedSpace},}/m", $indentationReplacement, $json); | |
$json = preg_replace("/\\n^\\s{{$leadingIndentedSpace},}([]}])(,?)\$/m", '$1$2', $json); | |
return $json; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP's JSON prettifier produces a lot of lines and indentation space on big JSON strings with many nested levels.
This encoder, gives you the option to remove the new lines and indentation from the indentation level you specify and higher.
This class also throws errors by default and has a consistent argument call order. It also assumes that decoding will be always associative (which I think we all use most of the time anyway).
Regex example: https://regex101.com/r/RW3ihP/1