我通过api在数据库中保存了一些值(所以我不能手动修改它)
当我从数据库返回时,json值不是有效的形式。我不想修改数据库中的每个值。我想在php中使用可以将其转换为有效格式的内容。
我的数据库中有这样的东西:
$invalid='{
"response": {
"id": "16"", <--------------------- Invalid Format(It can be for any key)
"event_name": "testing",
"image": "images/Penguins.jpg",
"event_date": "2014-12-13",
"event_time": "02:10",
"time_interval": "4",
"location": "mohali",
"event_type": "Rock",
"detail": "sfdsf fgf ghb\t",
"delivery": "dggh fghgfh\t\t",
"status": "1"
}
}';
那么如何通过php将其转换为有效的json:
$invalid='{
"response": {
"id": "16", <--------------------- valid Format
"event_name": "testing",
"image": "images/Penguins.jpg",
"event_date": "2014-12-13",
"event_time": "02:10",
"time_interval": "4",
"location": "mohali",
"event_type": "Rock",
"detail": "sfdsf fgf ghb\t",
"delivery": "dggh fghgfh\t\t",
"status": "1"
}
}';
答案 0 :(得分:0)
对于这个确切的情况,这将做:
<?php
$invalid='{
"response": {
"id": "16"",
"event_name": "testing",
"image": "images/Penguins.jpg",
"event_date": "2014-12-13",
"event_time": "02:10",
"time_interval": "4",
"location": "",
"event_type": "Rock"",
"detail": "sfdsf fgf ghb\t",
"delivery": "dggh fghgfh\t\t",
"status": "1""
},
"bar":{ "test": ""
}
}';
$invalid = explode("\n",$invalid);
foreach($invalid as $idx => &$line) {
$num = 0;
for($z=0;$z<strlen($line);++$z) {
$ch = $line[$z];
if($ch == "\\") {
++$z;
} else if($ch == '"') {
++$num;
$last_pos = $z;
}
}
if($num % 2 == 1) {
$line[$last_pos] = ' ';
}
}
$valid = implode("\n",$invalid);
print_r($valid);
输出:
{
"response": {
"id": "16" ,
"event_name": "testing",
"image": "images/Penguins.jpg",
"event_date": "2014-12-13",
"event_time": "02:10",
"time_interval": "4",
"location": "",
"event_type": "Rock" ,
"detail": "sfdsf fgf ghb\t",
"delivery": "dggh fghgfh\t\t",
"status": "1"
},
"bar":{ "test": ""
}
}
但我们确实建议修复数据库中的数据以及产生这些无效的表单/代码JSON
^^
答案 1 :(得分:-2)
它在哪些方面无效?如果仅存在双引号,则只使用preg_replace:
$valid = preg_replace('/""/','"',$invalid);