递归解码JSON字符串,直到解码的字符串是有效的JSON

时间:2017-11-29 15:39:34

标签: php json recursion urlencode urldecode

我有一次性的URL编码字符串:

$encodedJson = "%5B%7B%0A%09%22base%22%3A%20%7B%0A%09%09%22url%22%3A%20%22abc.com%22%2C%0A%09%09%22referrer%22%3A%20%22xyz.com%22%0A%09%7D%0A%7D%2C%20%7B%0A%09%22client%22%3A%20%7B%0A%09%09%22Pixel%22%3A%20false%2C%0A%09%09%22screen%22%3A%20%221680x1050%22%0A%09%7D%0A%7D%5D"

如果我使用以下函数,我有一个解码的JSON,它是一个数组:

$decodedJsonArray = json_decode(rawurldecode($encodedJson), true);

然后print_r($decodedJsonArray);给了我想要的输出:

Array
(
    [0] => Array
        (
            [base] => Array
                (
                    [url] => abc.com
                    [referrer] => xyz.com
                )

        )

    [1] => Array
        (
            [client] => Array
                (
                    [Pixel] => 
                    [screen] => 1680x1050
                )

        )

)

现在,让我们说我有一个多次URL编码的字符串:

$encodedJson = "%25255B%25257B%25250A%252509%252522base%252522%25253A%252520%25257B%25250A%252509%252509%252522url%252522%25253A%252520%252522abc.com%252522%25252C%25250A%252509%252509%252522referrer%252522%25253A%252520%252522xyz.com%252522%25250A%252509%25257D%25250A%25257D%25252C%252520%25257B%25250A%252509%252522client%252522%25253A%252520%25257B%25250A%252509%252509%252522Pixel%252522%25253A%252520false%25252C%25250A%252509%252509%252522screen%252522%25253A%252520%2525221680x1050%252522%25250A%252509%25257D%25250A%25257D%25255D"

此字符串是URL编码的三倍。现在,我想要实现与以前相同的JSON数组。我正在尝试编写类似于以下内容的函数:

function recursiveJsonDecode($encodedJson) {
    if (isJson($encodedJson)) {
        return $encodedJson;
    } else {
        $decodedJsonArray = json_decode(rawurldecode($encodedJson), true);
        return $decodedJsonArray;
    }
}

但它没有用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

json_decode会返回null,如果它不是有效的JSON,就像here所说:

  

如果无法解码json或者编码数据的深度超过递归限制,则返回NULL。

所以试试吧:

while(($decodedJsonArray = json_decode($encodedJson, true)) === null) {
    $encodedJson = rawurldecode($encodedJson);
}

print_r($decodedJsonArray);

使用isJson功能:

while(!isJson($encodedJson)) {
    $encodedJson = rawurldecode($encodedJson);
}
$decodedJsonArray = json_decode($encodedJson, true);

print_r($decodedJsonArray);