Skip to content

Instantly share code, notes, and snippets.

@collei
Last active August 28, 2023 17:50
Show Gist options
  • Save collei/bc3aae1d4eb2c3a8623cbe888b5c9be9 to your computer and use it in GitHub Desktop.
Save collei/bc3aae1d4eb2c3a8623cbe888b5c9be9 to your computer and use it in GitHub Desktop.
Code to pretty-output JSON to files
<?php
include 'JsonTextOutputter.php';
$dados = [
'arroz' => 16.1,
'feijao' => ['preto','branco','fradinho','azuki','carioca'],
'chip' => [
'fabricante' => 'Intel',
'modelo' => 'i9-12800',
'preco' => 3509.11,
'aplicacoes' => [
'tipos' => ['cientifico','profissional','caseiro','gamer','editor de video'],
'ranks' => [
['tier' => 1, 'quaker' => 1.00821],
['tier' => 2, 'quaker' => 1.00639],
['tier' => 3, 'quaker' => 1.00397],
['tier' => 4, 'quaker' => 1.00182],
['tier' => 5, 'quaker' => 1.00091],
]
],
]
];
$dados_json = json_encode($dados);
echo '<pre>' . JsonTextOutputter::print($dados_json) . '</pre>';
file_put_contents('./json-pretty-output.txt', JsonTextOutputter::print($dados_json));
<?php
/**
* @class \JsonTextOutputter
* @author Kendall Hopkins @link https://stackoverflow.com/users/188044/kendall-hopkins
* @author George G @link https://stackoverflow.com/users/3172092/george-g
* @source https://stackoverflow.com/a/9776726/21986565
**/
class JsonTextOutputter
{
/**
* Outputs pretty-formatted JSON string
*
* @param string $json
* @return string
**/
public static function print($json)
{
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
//
for( $i = 0; $i < $json_length; $i++ ) {
// current char
$char = $json[$i];
// indentation
$new_line_level = NULL;
// partial results
$post = "";
//
// if no indent set...
//
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
//
// controls indentation level
//
if ($in_escape) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}':
case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{':
case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ":
case "\t":
case "\n":
case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} elseif ($char === '\\') {
$in_escape = true;
}
//
// applies current indented level
//
if ($new_line_level !== NULL) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
// aggregates partials to full result
$result .= $char.$post;
}
//
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment