note 103269 deleted from function.json-encode by danbrown

From: Date: Tue, 05 Apr 2011 15:05:23 +0000
Subject: note 103269 deleted from function.json-encode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-178516@lists.php.net to get a copy of this message
Note Submitter: andrew at quizlet dot com ---- umbrae's json_format for indenting json has a bug in it when you pass in raw strings, like this: <?php echo json_format('"plain string"'); ?> The fix is in the case '"' section, where we must check if the first character is a ". Here is the complete correct function: <?php function json_indent($json) { $tab = " "; $new_json = ""; $indent_level = 0; $in_string = false; $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; } ?>

« previous php.notes (#178516) next »