{trend : 3, yearLowPrice : 99.9, points : [['2014-10-29',139.9], ...]}
不合法之處:鍵名無雙引號、字符串用單引號、尾逗號等。
$raw = <<<'JSON'
{trend : 3, yearLowPrice : 99.9, points : [['2014-10-29',139.9],['2014-11-11',115.9]]}
JSON;
// 1. 鍵名加雙引號
$json = preg_replace_callback('/([a-zA-Z0-9_]+)\s*:/', function($m) {
return '"' . $m[1] . '":';
}, $raw);
// 2. 單引號字符串轉雙引號(簡易,假設無嵌套單引號)
$json = str_replace("'", '"', $json);
// 3. 移除尾隨逗號
$json = preg_replace('/,\s*([}\]])/', '$1', $json);
// 4. 解析
$arr = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('JSON 解析失敗: ' . json_last_error_msg());
}
print_r($arr);
Array
(
[trend] => 3
[yearLowPrice] => 99.9
[points] => Array
(
[0] => Array ( [0] => 2014-10-29 [1] => 139.9 )
[1] => Array ( [0] => 2014-11-11 [1] => 115.9 )
)
)
composer require seld/jsonlint 先驗證/修復json_encode)JsonMachine