For those of you who prefer a more object oriented approach (as I do), here is a fairly simple wrapper that handles errors using exceptions:
<?php
class JSON
{
public static function Encode($obj)
{
return json_encode($obj);
}
public static function Decode($json, $toAssoc = false)
{
$result = json_decode($json, $toAssoc);
switch(json_last_error())
{
case JSON_ERROR_DEPTH:
$error = ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
$error = ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$error = ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_NONE:
default:
$error = '';
}
if (!empty($error))
throw new Exception('JSON Error: '.$error);
return $result;
}
}
?>
json_last_error
(PHP 5 >= 5.3.0)
json_last_error — 直近に発生したエラーを返す
説明
int json_last_error
( void
)
直近の JSON パース処理中に発生したエラー (もし存在すれば) を返します。
パラメータ
この関数にはパラメータはありません。
返り値
整数値を返します。これは、次の定数のいずれかとなります。
| 定数 | 意味 |
|---|---|
| JSON_ERROR_NONE | エラーは発生しませんでした |
| JSON_ERROR_DEPTH | スタックの深さの最大値を超えました |
| JSON_ERROR_CTRL_CHAR | 制御文字エラー。おそらくエンコーディングが違います |
| JSON_ERROR_SYNTAX | 構文エラー |
例
例1 json_last_error() の例
<?php
// 正しい json 文字列
$json[] = '{"Organization": "PHP Documentation Team"}';
// 間違った json 文字列で、構文エラーとなります
// ここでは、クォートに " ではなく ' を使用しています
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach($json as $string)
{
echo 'Decoding: ' . $string;
json_decode($string);
switch(json_last_error())
{
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_NONE:
echo ' - No errors';
break;
}
echo PHP_EOL;
}
?>
上の例の出力は以下となります。
Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON
json_last_error
lior at mytopia dot com
09-Mar-2009 10:17
09-Mar-2009 10:17
