示例代码:
<?php
$json = "['foo', 'bar']";
var_dump( json_decode($json) );
它在我的机器上运行PHP 5.5.3,但在其他地方失败。
我知道这是不正确的JSON,但我的web服务给我JSON与'
符号一起"
['foo', "bar", {'test': "crazy \"markup\""}]
如何在PHP 5.3中用撇号解析JSON数据?很显然,我想解析的原始JSON更复杂。
(我无法在生产服务器上升级我的PHP,也无法从webservice获取正确的JSON)
发布于 2018-03-28 09:48:02
这里有一个简单的解析器,可以为你解决报价问题。如果遇到'
不是双引号的报价"
,它会认为它是错误的,并替换该报价中的双引号,然后将引号括起来变成双引号:
示例:
<?php
function fixJSON($json) {
$newJSON = '';
$jsonLength = strlen($json);
for ($i = 0; $i < $jsonLength; $i++) {
if ($json[$i] == '"' || $json[$i] == "'") {
$nextQuote = strpos($json, $json[$i], $i + 1);
$quoteContent = substr($json, $i + 1, $nextQuote - $i - 1);
$newJSON .= '"' . str_replace('"', "'", $quoteContent) . '"';
$i = $nextQuote;
} else {
$newJSON .= $json[$i];
}
}
return $newJSON;
}
$brokenJSON = "['foo', {\"bar\": \"hel'lo\", \"foo\": 'ba\"r'}]";
$fixedJSON = fixJSON( $brokenJSON );
var_dump($fixedJSON);
print_r( json_decode( $fixedJSON ) );
?>
输出:
string(41) "["foo", {"bar": "hel'lo", "foo": "ba'r"}]"
Array
(
[0] => foo
[1] => stdClass Object
(
[bar] => hel'lo
[foo] => ba'r
)
)
https://stackoverflow.com/questions/-100007820
复制相似问题