如何解析此json进入响应

时间:2018-09-12 09:17:02

标签: php json laravel

我知道这是无效的json,但我正在从creditswitch api得到此json作为响应,我无法更改此响应,但我想解析此json
当我替换这个只是细节键

desired json response
{
    "statusCode": "00",
    "statusDescription": {
        "customerNo": 283375350,
        "accountStatus": "OPEN",
        "firstname": "ADVENTURE",
        "lastname": "MOBILE",
        "customerType": "SUD",
        "invoicePeriod": 1,
        "dueDate": "2018-09-29T00:00:00+01:00"
    }
}

我得到了有效的json,但是如何删除json的第一部分,我不知道下面的解决方案是我得到的原始json。

this is the original json response
{
    "details": {
        "number": "10553886499",
        "requestType": "VALIDATE_DEVICE_NUMBER"
    },
    "serviceId": "AQA"
} 
{
    "statusCode": "00",
    "statusDescription": {
        "customerNo": 283375350,
        "accountStatus": "OPEN",
        "firstname": "ADVENTURE",
        "lastname": "MOBILE",
        "customerType": "SUD",
        "invoicePeriod": 1,
        "dueDate": "2018-09-29T00:00:00+01:00"
    }
}

1 个答案:

答案 0 :(得分:1)

因此,很明显,此API一次输出两个json对象,这是非标准的,并混淆了php json解码器。我认为您可以对preg_match进行巧妙的拆分,尽管子序列非常复杂。我创建了这个小例程,似乎可以将它们拆分为可解码的部分

$input=<<<DAT
{
    "details": {
        "number": "10553886499",
        "requestType": "VALIDATE_DEVICE_NUMBER"
    },
    "serviceId": "AQA"
} 
{
    "statusCode": "00",
    "statusDescription": {
        "customerNo": 283375350,
        "accountStatus": "OPEN",
        "firstname": "ADVENTURE",
        "lastname": "MOBILE",
        "customerType": "SUD",
        "invoicePeriod": 1,
        "dueDate": "2018-09-29T00:00:00+01:00"
    }
}
DAT;

$cur_json='';
$requests=[];
$inbrace=false;
$inquotes=false;
$inescape=false;
$bracecnt=0;
for($i=0;$i<mb_strlen($input);$i++){
    $c=mb_substr($input,$i,1);
    switch($c){
        case '{':
            if(!$inbrace)
                $inbrace=true;
            $bracecnt++;
            $cur_json.=$c;
            break;
        case '}':
            if($inquotes)
                $cur_json.=$c;
            else{
                $bracecnt--;
                $cur_json.=$c;
                if($bracecnt==0)
                {
                    $inbrace=false;
                    $requests[]=$cur_json;
                    $cur_json='';
                }
            }
            break;
        case '"':
            $cur_json.=$c;
            if(!$inescape&&$inquotes)
                $inquotes=false;
            else
                $inquotes=true;
            break;
        case '\\':
            $cur_json.=$c;
            if(!$inescape)
                $inescape=true;
            else
                $inescape=false;
            break;
        default:
            $cur_json.=$c;
            break;
    }
}
$requests[]=$cur_json;

echo '<pre>';
var_dump(json_decode($requests[0]));
var_dump(json_decode($requests[1]));