note 99343 deleted from function.json-decode by danbrown

From: Date: Thu, 12 Aug 2010 00:51:33 +0000
Subject: note 99343 deleted from function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-171590@lists.php.net to get a copy of this message
Note Submitter: scott at pawprint dot net ---- thanks to what I found from the comments here I'm attaching a pair of functions that will generate an object structure identical to json_decode from PHP > 5.2 for those still on older PHP versions - based on the function from www at walidator dot info but returning an object rather then arrays. The intent is a direct drop-in replacement for the new built-in decoder. function processJsonObj($pSuffix=0, $json){ $vInQuote = false; $vNextSuffix = $pSuffix; $vPreCode = ''; $vTempJSON = '$oJson'.$pSuffix.' = new stdClass();'."\n"; $vTempJSON.= '$oJson'.$pSuffix.'->'; $vOIdx = 1; $vAIdx = 0; for($i=0; $i < strlen($json); $i++){ if(!$vInQuote){ if($vOIdx == 1){ if($json[$i] == '{') { $vNextSuffix++; $vTempJSON.= '$oJson'.$vNextSuffix; $vPreCode .= '$oJson'. $vNextSuffix.' = processJsonObj('.$vNextSuffix.',\''; $vOIdx++; }elseif($json[$i] == '[') { $vTempJSON .= ' array('; $vAIdx++; }elseif($json[$i] == ']'){ $vTempJSON .= ')'; $vAIdx--; }elseif(($vAIdx == 0) && ($json[$i] == ',')){ $vTempJSON .= ';'."\n".'$oJson'.$pSuffix.'->'; }elseif($json[$i] == ':'){ $vTempJSON .= ' = '; }else{ $vTempJSON .= $json[$i]; } }else{ if($json[$i] == '{'){ $vOIdx++; $vPreCode .= $json[$i]; }elseif($json[$i] == '}'){ $vOIdx--; if($vOIdx == 1){ $vPreCode .= '\');'."\n"; }else{ $vPreCode .= $json[$i]; } }else{ $vPreCode .= $json[$i]; } } }else{ $vTempJSON .= $json[$i]; } if(($vOIdx == 1) && ($json[$i] == '"')){ $vInQuote = !$vInQuote; } } if(preg_match_all('/\-\>?("[^=]*")/', $vTempJSON, $vRegs, PREG_SET_ORDER)){ foreach($vRegs as $vKey => $vMatch){ $vTempJSON = str_replace($vMatch[1], trim(str_replace('"','',$vMatch[1])),$vTempJSON); } } $vFinalCode = $vPreCode."\n".$vTempJSON.';'; eval($vFinalCode); $vOutput = 'oJson'.$pSuffix; return $$vOutput; } /*=================================*/ function json_decode($json){ $comment = false; $vTempJSON = ''; $json = str_replace(array("\n","\r"),"",$json); $json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":', $json); $json = preg_replace('/^{/','',$json); $json = preg_replace('/}$/','',$json); $vJsonObj = processJsonObj(0, trim($json)); return $vJsonObj; }

« previous php.notes (#171590) next »