Skip to content

Instantly share code, notes, and snippets.

@itsjavi
Last active March 5, 2021 15:43
Show Gist options
  • Save itsjavi/b8b575e21c3bcc768e347c0e5f9ed5f0 to your computer and use it in GitHub Desktop.
Save itsjavi/b8b575e21c3bcc768e347c0e5f9ed5f0 to your computer and use it in GitHub Desktop.
PHP json_encode prettify compact mode with indentation level options
<?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;
}
}
@itsjavi
Copy link
Author

itsjavi commented Jan 29, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment