采集JSON解析错误的修复

两段采集来的JSON格式:

一:

复制代码
{"hwgOnlineId":"554312", "jiwuChatId":"", "phoneCategoryId":"20006", "cuxiaoSeq":{voucherTitle:1,lh

二:

复制代码
{"pic":"//imgservice.suning.cn/uimg1/b2c/image/rX4cM65dyr_4kndNFwLEgA.jpg_400w_400h_4e",
	 "itemDomain":"//"+document.location.hostname,
	 "resRoot":"//script.suning.cn/project/pdsWeb",
	 "shopCount":1,
	 "sslStoreCode":"",
	 "addCartNumLimit":"199",
	 "favoriteStatusSwitch":"1" == "1",
	 "thirdEVoucherFlag":"",
	 "specialSSLFlag":"",
	 "sslLabelText" : "苏宁服务"}

直接使用PHP的json_decode报错

解决思路:

1、手动格式化,将所有","换行

2、半分法删除内容定位报错的代码行

3、找到问题行后过滤格式处理

4、对于json格式中掺杂了javascript代码的情况还可以直接使用v8js引擎处理

解决方案一(修复格式):

复制代码
$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扩展):

复制代码
//以JavaScript环境执行JS
function getJsJSON($str){
    $v8 = new V8Js();
    $func = "
        function getJsJSON(str){
         document ={location:{hostname:''}}
         a={$str}
         return JSON.stringify(a);
        }
        b = getJsJSON()
   ";
 
   try {
        //传递参数给js
        // $v8->str = $str;
        //执行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
相关推荐
隐积3 小时前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
名字还没想好☜6 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
初级代码游戏7 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
酷在前行8 小时前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr8288 小时前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
废弃的小码农9 小时前
功能测试--Day07--Python编程基础
开发语言·python
fengci.9 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
程序员zgh10 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
念何架构之路10 小时前
restartmanager-重启管理子系统
java·开发语言
SomeB1oody11 小时前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程