如何json_decode无效的JSON与撇号而不是引号

Pet*_*ter 19 php json

示例代码:

<?php

$json = "['foo', 'bar']";

var_dump( json_decode($json) );
Run Code Online (Sandbox Code Playgroud)

它适用于PHP 5.5.3,但它不适用于较低的PHP版本

它可以在我的机器上使用PHP 5.5.3,但在其他地方都失败了.

我知道这是不正确的JSON,但我的webservice给了我带'符号的JSON"

['foo', "bar", {'test': "crazy \"markup\""}]
Run Code Online (Sandbox Code Playgroud)

砂箱

如何在PHP 5.3中使用撇号解析JSON数据?显然,我想解析的原始JSON更复杂.

(我无法在生产服务器上升级我的PHP,也无法从webservice获取正确的JSON)

Nik*_*kiC 33

以下是此问题的替代解决方案:

function fixJSON($json) {
    $regex = <<<'REGEX'
~
    "[^"\\]*(?:\\.|[^"\\]*)*"
    (*SKIP)(*F)
  | '([^'\\]*(?:\\.|[^'\\]*)*)'
~x
REGEX;

    return preg_replace_callback($regex, function($matches) {
        return '"' . preg_replace('~\\\\.(*SKIP)(*F)|"~', '\\"', $matches[1]) . '"';
    }, $json);
}
Run Code Online (Sandbox Code Playgroud)

这种方法在两个方面比h2ooooooo的功能更强大:

  • 它通过对它们应用额外的转义来保留单引号字符串中出现的双引号.h2o的变体将用双引号替换它们,从而改变字符串的值.
  • 它将正确处理转义的双引号\",因为h2o的版本似乎进入无限循环.

测试:

$brokenJSON = <<<'JSON'
['foo', {"bar": "hel'lo", "foo": 'ba"r ba\"z', "baz": "wor\"ld ' test"}]
JSON;

$fixedJSON = fixJSON($brokenJSON);
$decoded = json_decode($fixedJSON);

var_dump($fixedJSON);
print_r($decoded);
Run Code Online (Sandbox Code Playgroud)

输出:

string(74) "["foo", {"bar": "hel'lo", "foo": "ba\"r ba\"z", "baz": "wor\"ld ' test"}]"
Array
(
    [0] => foo
    [1] => stdClass Object
        (
            [bar] => hel'lo
            [foo] => ba"r ba"z
            [baz] => wor"ld ' test
        )
)
Run Code Online (Sandbox Code Playgroud)


h2o*_*ooo 6

这是一个简单的解析器,可以为您修复报价.如果遇到'不是双引号的引用",它会认为它是错的并替换该引号内的双引号,并将引号括起来用双引号:

示例:

<?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 ) );
?>
Run Code Online (Sandbox Code Playgroud)

输出:

string(41) "["foo", {"bar": "hel'lo", "foo": "ba'r"}]"
Array
(
    [0] => foo
    [1] => stdClass Object
        (
            [bar] => hel'lo
            [foo] => ba'r
        )

)
Run Code Online (Sandbox Code Playgroud)

DEMO