Skip to content

Instantly share code, notes, and snippets.

@firewalker06
Created February 2, 2013 04:07
Show Gist options
  • Save firewalker06/4696072 to your computer and use it in GitHub Desktop.
Save firewalker06/4696072 to your computer and use it in GitHub Desktop.
Beautify JSON, copied from http://pastebin.com/xB0fG9py
<?php
/**
* @author Marcelius 'mardagz' Dagpin
* @name Beautify JSON
* @copyright 2012
* @uses /
* $json_array = array(
* "name" => "mardagz",
* "gender" => "lalaki po akow hihihi",
* "age" => 40
* );
*
* $json_data = json_encode($json_array);
*
* print $json->beautify_json($json_data);
*
*/
class PRETTY_JSON{
function beautify_json($json) {
$tab = " ";
$new_json = "";
$indent_level = 0;
$in_string = false;
$json_obj = json_decode($json);
if($json_obj === false)
return false;
$json = json_encode($json_obj);
$len = strlen($json);
for($c = 0; $c < $len; $c++)
{
$char = $json[$c];
switch($char)
{
case '{':
case '[':
if(!$in_string)
{
$new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
$indent_level++;
}
else
{
$new_json .= $char;
}
break;
case '}':
case ']':
if(!$in_string)
{
$indent_level--;
$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
}
else
{
$new_json .= $char;
}
break;
case ',':
if(!$in_string)
{
$new_json .= ",\n" . str_repeat($tab, $indent_level);
}
else
{
$new_json .= $char;
}
break;
case ':':
if(!$in_string)
{
$new_json .= ": ";
}
else
{
$new_json .= $char;
}
break;
case '"':
if($c > 0 && $json[$c-1] != '\\')
{
$in_string = !$in_string;
}
default:
$new_json .= $char;
break;
}
}
return $new_json;
}
}
$json = new PRETTY_JSON();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment