[PHP] json_decode return null
最近串某平台的帳號,對方 return 回來的資料是 josn 格式,可是我用 json_decode()
卻解不開,回傳 null。
幸好後來有查到解決方法,用
$a = "[{key1:'value1',key2:'value2'}]";
var_dump(json_decode($a));
// 結果
null
我仔細看了一下回傳回來的 json 字串,key 值沒有用雙引號包起來,而且 value
用的也是單引號。難道我要自己把他格式化在解開嗎,感覺有點蠢。幸好後來有查到解決方法,用
preg_replace('@([\w_0-9]+):@', '"\1":', str_replace('\'', '"', $a));
處理一下字串,就可以 decode 成功。
$a = "[{key1:'value1',key2:'value2'}]";
$a = preg_replace('@([\w_0-9]+):@', '"\1":', str_replace('\'', '"', $a));
var_dump(json_decode($a));
// 結果
array(1) {
[0]=>
object(stdClass)#1 (11) {
["key1"]=>
string(6) "value1"
["key2"]=>
string(6) "value2"
}
}
參考文件
留言
張貼留言