Had a similar problem, in that I was posting a serialised javascript object to a php script and wished to save it to the server in a human-readable format.
Found this post on the webdeveloper.com forum and tweaked the code very slightly to suit my own sensibilities (it takes a json encoded string):
function jsonToReadable($json){
$tc = 0; //tab count
$r = ''; //result
$q = false; //quotes
$t = "\t"; //tab
$nl = "\n"; //new line
for($i=0;$i<strlen($json);$i++){
$c = $json[$i];
if($c=='"' && $json[$i-1]!='\\') $q = !$q;
if($q){
$r .= $c;
continue;
}
switch($c){
case '{':
case '[':
$r .= $c . $nl . str_repeat($t, ++$tc);
break;
case '}':
case ']':
$r .= $nl . str_repeat($t, --$tc) . $c;
break;
case ',':
$r .= $c;
if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);
break;
case ':':
$r .= $c . ' ';
break;
default:
$r .= $c;
}
}
return $r;
}
passing in
{"object":{"array":["one","two"],"sub-object":{"one":"string","two":2}}}
returns
{
"object": {
"array": [
"one",
"two"
],
"sub-object": {
"one": "string",
"two": 2
}
}
}