note 103269 added to function.json-encode
| From: | andrew at quizlet dot com | Date: | Tue, 05 Apr 2011 07:03:24 +0000 |
| Subject: | note 103269 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-178504@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 18.248.5.150
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/103269
Del: integrated -- https://master.php.net/note/delete/103269/integrated
Del: useless -- https://master.php.net/note/delete/103269/useless
Del: bad code -- https://master.php.net/note/delete/103269/bad+code
Del: spam -- https://master.php.net/note/delete/103269/spam
Del: non-english -- https://master.php.net/note/delete/103269/non-english
Del: in docs -- https://master.php.net/note/delete/103269/in+docs
Del: other reasons-- https://master.php.net/note/delete/103269
Reject -- https://master.php.net/note/reject/103269
Search -- https://master.php.net/manage/user-notes.php