note 105259 deleted from function.json-decode by googleguy
| From: | googleguy@php.net | Date: | Fri, 30 Nov 2012 05:45:41 +0000 |
| Subject: | note 105259 deleted from function.json-decode by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192221@lists.php.net to get a copy of this message | ||
Note Submitter: Dragos.U
----
Hmm, using eval without proper escaping of the input value .. will not get you anything good ;)
Here is my JSON decode function, it does not decode to PHP object/array but only to an array (can be
easily changed anyway).
<?php
function jsonDecode ($json)
{
$json = str_replace(array("\\\\", "\\\""), array("\",
"""), $json);
$parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $index => $part)
{
if (strlen($part) == 1)
{
switch ($part)
{
case "[":
case "{":
$parts[$index] = "array(";
break;
case "]":
case "}":
$parts[$index] = ")";
break;
case ":":
$parts[$index] = "=>";
break;
case ",":
break;
default:
return null;
}
}
else
{
if ((substr($part, 0, 1) != "\"") || (substr($part, -1, 1) !=
"\""))
{
return null;
}
}
}
$json = str_replace(array("\", """, "$"),
array("\\\\", "\\\"", "\\$"), implode("", $parts));
return eval("return $json;");
}
?>
How it works:
it searches for the "..." (that can be a key or a value) so we need to make sure we do not
take into account something like ...\"... that is not the end of the key/value but escaped
value for the doublequote. That's why we first replace \\ (escaped backslash) and then we can
look for a ...\"... and be sure it's not a ...\\" (the end of the key/value).
Next we split the string into chunks, any other characters outside of the "..." only need
to be []{},: (and spaces, but those we can throw away).
Next we do a little bit of checking on the data, be sure we have valid JSON and replace some of the
characters on the way (so we can 'eval' as PHP code later).
Then we replace back the initial changed characters and escape $ (!!!) because we will use
'eval' with values of the array (keys and values) in double quotes.
(http://php.net/manual/en/language.types.string.php)
The function will return NULL for invalid JSON.
;)