兩段采集來的JSON格式:
一:
{"hwgOnlineId":"554312", "jiwuChatId":"", "phoneCategoryId":"20006", "cuxiaoSeq":{voucherTitle:1,lh
二:
{"pic":"http://imgservice.suning.cn/uimg1/b2c/image/rX4cM65dyr_4kndNFwLEgA.jpg_400w_400h_4e",
"itemDomain":"http://"+document.location.hostname,
"resRoot":"http://script.suning.cn/project/pdsWeb",
"shopCount":1,
"sslStoreCode":"",
"addCartNumLimit":"199",
"favoriteStatusSwitch":"1" == "1",
"thirdEVoucherFlag":"",
"specialSSLFlag":"",
"sslLabelText" : "蘇寧服務(wù)"}
直接使用PHP的json_decode報錯
解決思路:
1、手動格式化,將所有","換行
2、半分法刪除內(nèi)容定位報錯的代碼行
3、找到問題行后過濾格式處理
4、對于json格式中摻雜了javascript代碼的情況還可以直接使用v8js引擎處理
解決方案一(修復(fù)格式):
$str = file_get_contents('test.txt');
$str = preg_replace('@/\*[^/]+\*/@isU','',$str);
$str = str_replace('"+document.location.hostname','"',$str);
$str = str_replace('"1" == "1"','true',$str);
$json = json_decode($str);
if(!$json) $json = json2array($str);
var_dump(getJsJSON($json));
解決方案二(使用PHP-V8JS擴(kuò)展):
//以JavaScript環(huán)境執(zhí)行JS
function getJsJSON($str){
$v8 = new V8Js();
$func = "
function getJsJSON(str){
document ={location:{hostname:''}}
a={$str}
return JSON.stringify(a);
}
b = getJsJSON()
";
try {
//傳遞參數(shù)給js
// $v8->str = $str;
//執(zhí)行js
$code = $v8->executeString($func);
//清空對象,垃圾回收。
unset($v8);
} catch (V8JsScriptException $e) {
dump($e->getMessage());
dump($e->getJsSourceLine());
dump($e->getJsTrace());
// dump($e);
}
if($code)$code=json_decode($code,true);
return $code;
}
$js = file_get_contents('test.txt');
var_dump(getJsJSON($js));
o0b.cn/ibrad