我从这样的api获取JSON字符串:
{ "title":"Example string's with "special" characters" }
使用json_decode无法将其解码为json(其输出为null)。
所以我想将其更改为json可解码的内容,例如:
{ "title":"Example string's with \"special\" characters" }
或者
{ "title":"Example string's with 'special' characters" }
为了使json_decode函数正常工作,我该怎么办?
从昨天开始,我一直在尝试解决这个棘手的问题,在拉了很多头发之后,我想到了这个解决方案。
首先,让我们澄清一下我们的假设。
分析问题:
我们知道json键的格式如下(,“ keyString” :),而json值是(:“ valueString”,)
keyString:是除(:“)以外的任何字符序列。
valueString:是除(“,)以外的任何字符序列。
我们的目标是转义valueString内的引号,以实现我们需要将keyStrings和valueStrings分开。
现在,在分析问题之后,我们可以说
解决方案:使用此事实,代码将是
function escapeJsonValues($json_str){
$patern = '~(?:,\s*"((?:.(?!"\s*:))+.)"\s*(?=\:))(?:\:\s*(?:(\d+)|("\s*")|(?:"((?!\s*")(?:.(?!"\s*,))+.)")))~';
//remove { }
$json_str = rtrim(trim(trim($json_str),'{'),'}');
if(strlen($json_str)<5) {
//not valid json string;
return null;
}
//put , at the start nad the end of the string
$json_str = ($json_str[strlen($json_str)-1] ===',') ?','.$json_str :','.$json_str.',';
//strip all new lines from the string
$json_str=preg_replace('~[\r\n\t]~','',$json_str);
preg_match_all($patern, $json_str, $matches);
$json='{';
for($i=0;$i<count($matches[0]);$i++){
$json.='"'.$matches[1][$i].'":';
//value is digit
if(strlen($matches[2][$i])>0){
$json.=$matches[2][$i].',';
}
//no value
elseif (strlen($matches[3][$i])>0) {
$json.='"",';
}
//text, and now we can see if there is quotations it will be related to the text not json
//so we can add slashes safely
//also foreword slashes should be escaped
else{
$json.='"'.str_replace(['\\','"' ],['/','\"'],$matches[4][$i]).'",';
}
}
return trim(rtrim($json,','),',').'}';
}
注意:该代码实现空格。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句