最新消息:觉得本站不错的话 记得收藏哦 博客内某些功能仅供测试 讨论群:135931704 快养不起小站了 各位有闲钱就打赏下把 My Email weicots#gmail.com Please replace # with @

php 解析非标准Json(单引号)格式数据处理办法

PHP ajiang-tuzi 4401浏览

非标准的json 格式示例

{'asin': '0001048791', 'salesRank': {'Books': 6334800}, 'imUrl': 'http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg', 'categories': [['Books']], 'title': 'The Crucible: Performed by Stuart Pankin, Jerome Dempsey & Cast'}

处理示例

$string = "{'asin': '0001048791', 'salesRank': {'Books': 6334800}, 'imUrl': 'http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg', 'categories': [['Books']], 'title': 'The Crucible: Performed by Stuart Pankin, Jerome Dempsey & Cast'}";

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

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

$decoded = json_decode($fixedJSON);

var_dump($fixedJSON);
print_r($decoded);

输出

stdClass Object
(
    [asin] => 0001048791
    [salesRank] => stdClass Object
        (
            [Books] => 6334800
        )

    [imUrl] => http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg
    [categories] => Array
        (
            [0] => Array
                (
                    [0] => Books
                )

        )

    [title] => The Crucible: Performed by Stuart Pankin, Jerome Dempsey & Cast
)

转载请注明:(●--●) Hello.My Weicot » php 解析非标准Json(单引号)格式数据处理办法

蜀ICP备15020253号-1