$json = '{"name":"John","age":30}';
$res = json_decode($json);
echo $res['name']; // 錯誤:Cannot use object of type stdClass as array
json_decode() 預設回傳 stdClass 物件,不能用 [] 陣列語法存取。
$res = json_decode($json, true); // 強制回傳關聯陣列 echo $res['name']; // 正常輸出 "John"
$res = json_decode($json); // 預設回傳物件 echo $res->name; // 使用 -> 存取屬性
$json = '{"user":{"id":1,"tags":["php","json"]},"status":true}';
// 方法一:陣列
$data = json_decode($json, true);
echo $data['user']['tags'][0]; // php
// 方法二:物件
$obj = json_decode($json);
echo $obj->user->tags[0]; // php
json_decode 回傳 null,請用 json_last_error() / json_last_error_msg() 診斷。JSON_BIGINT_AS_STRING 旗標 (PHP 5.4+) 保持字串。// 完整範例:錯誤處理 + 大整數保持字串
$json = '{"big_id": 12345678901234567890}';
$data = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('JSON 解析失敗: ' . json_last_error_msg());
}
var_dump($data['big_id']); // string(20) "12345678901234567890"