PHP 5.2 才內建 json_decode,舊版本需自行實現或使用第三方庫。
<?php
function json_decode2($json) {
$comment = false;
$out = '$x=';
for ($i=0; $i<strlen($json); $i++) {
if (!$comment) {
if ($json[$i]=='{' || $json[$i]=='[') $out .= ' array(';
elseif ($json[$i]=='}' || $json[$i]==']') $out .= ')';
elseif ($json[$i]==':') $out .= '=>';
else $out .= $json[$i];
} else {
$out .= $json[$i];
}
if ($json[$i]=='"' && $json[$i-1]!='\\') $comment = !$comment;
}
eval($out . ';');
return $x;
}
?>
缺點:使用 eval 有安全風險,且只返回陣列,不支援物件。
PEAR Services_JSON 類純 PHP 實現,支援物件與陣列雙向轉換,相容 PHP 4/5:
require_once 'Services/JSON.php';
$json = new Services_JSON();
$arr = $json->decode($jsonString);
$str = $json->encode($phpVar);
下載:PEAR Services_JSON 或 GitHub 眾多移植版。
json_encode/decode。eval 方案。