Skip to content

Instantly share code, notes, and snippets.

@d4rkne55
Created September 20, 2019 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d4rkne55/f300c995ee7d2f7134b80eb66484bee2 to your computer and use it in GitHub Desktop.
Save d4rkne55/f300c995ee7d2f7134b80eb66484bee2 to your computer and use it in GitHub Desktop.
Class for dumping/beautifying JSON
<?php
class JsonDumper
{
/** @var string */
private $json;
/** @var int spaces to use for one indentation level */
private $indentation;
public function __construct($json, $indentation = 4) {
// TODO: check if json is valid first
$this->json = $json;
$this->indentation = $indentation;
$this->process();
}
private function process() {
$pos = 0;
$currentIndent = 0;
while (($nextPos = $this->getNextToken($pos)) !== false) {
$newLine = true;
// if a token is at current position
if ($nextPos === $pos) {
$token = $this->json[$pos];
if ($token == '}' || $token == ']') {
$currentIndent -= $this->indentation;
$newLine = false;
echo "\n", str_repeat(' ', $currentIndent);
} elseif ($token == '{' || $token == '[') {
$currentIndent += $this->indentation;
}
echo $token;
if ($token == ':') {
$newLine = false;
echo ' ';
}
$pos++;
}
if ($newLine) {
echo "\n", str_repeat(' ', $currentIndent);
}
$nextPos = ($this->getNextToken($pos) !== false) ? $this->getNextToken($pos) : strlen($this->json);
echo substr($this->json, $pos, $nextPos - $pos);
$pos = $nextPos;
}
}
private function getNextToken($currentPos) {
$tokens = '{}[]:,';
$regex = preg_quote($tokens);
preg_match("/[$regex]/", $this->json, $matches, PREG_OFFSET_CAPTURE, $currentPos);
if (isset($matches[0][1])) {
return $matches[0][1];
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment