note 105259 added to function.json-decode

From: Date: Fri, 05 Aug 2011 13:52:58 +0000
Subject: note 105259 added to function.json-decode
Groups: php.notes 
Request: Send a blank email to php-notes+get-182250@lists.php.net to get a copy of this message
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). 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. ;) ---- Server IP: 69.147.83.197 Probable Submitter: 188.215.101.215 ---- Manual Page -- http://www.php.net/manual/en/function.json-decode.php Edit -- https://master.php.net/note/edit/105259 Del: integrated -- https://master.php.net/note/delete/105259/integrated Del: useless -- https://master.php.net/note/delete/105259/useless Del: bad code -- https://master.php.net/note/delete/105259/bad+code Del: spam -- https://master.php.net/note/delete/105259/spam Del: non-english -- https://master.php.net/note/delete/105259/non-english Del: in docs -- https://master.php.net/note/delete/105259/in+docs Del: other reasons-- https://master.php.net/note/delete/105259 Reject -- https://master.php.net/note/reject/105259 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#182250) next »