php - How to parse this json getting in the response
问题描述
i know this is invalid json but i am getting this json in response from creditswitch api i cannot change this response but i want to parse this json
when i replace this just details key like
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"
}
}
i get valid json but how to remove that 1st part of json i dont know any solution over it following is the original json i am getting.
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"
}
}
解决方案
So, obviously this API is outputting two json objects at a time, which isn't standard, and confuses php json decoder. I think you could do something clever with preg_match
to split, though it's quite complicated with subsequences. I have created this little routine that seems to work at splitting these into parts that are decodable
$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]));
推荐阅读
- google-cloud-platform - 如何通过 terraform 使用服务帐户创建谷歌云 pubsub 订阅?
- python - 使用 python 读取 MS sharepoint.SharepointListItem
- javascript - 是否可以使用 vanilla JavaScript 而不是 react.js 来渲染网站的一部分?
- cassandra - 在 Cassandra 中,为什么单个值优先于仲裁节点空响应?
- javascript - 如何在 React 中显示数组?
- vim - 为什么否定字符类不能按预期工作?
- android - SeekBar 无法与来自服务器的流式音频一起正常工作
- python-3.x - Discord.py 将参数添加到 api 命令
- html - 在我学校的网页上,我们希望自动更新专业列表。如何链接领英?
- python - 使用 re.sub() 从匹配的模式中删除空格