php代码将无效的json字符串转换为有效的json字符串

时间:2016-09-12 12:31:14

标签: php json

如何在php中将以下无效的json字符串转换为有效 我需要在PHP中的解决方案。 请给我一个方法将此输入json转换为输出json

输入:

{
            account : 'rogersrmisports',
            brand : 'Sportsnet',
            tags : '',
            cmsid : '2912963',
            wordCount : '3197',
            publishDate : 'July 11, 2016',
            products : '',
            pages : 'sportsnet : hockey : nhl : david amber q&a, part i: \'my job is not to be ron jr.\'',
            section : 'sportsnet : hockey',
            subSection : 'sportsnet : hockey : nhl',
            contentName : 'david amber q&a, part i: \'my job is not to be ron jr.\'',
            complete90percent : false, // default: false
        }

输出:

{
            "account" : "rogersrmisports",
            "brand" : "Sportsnet",
            "tags" : "",
            "cmsid" : "2912963",
            "wordCount" : "3197",
            "publishDate" : "July 11, 2016",
            "products" : "",
            "pages" : "sportsnet : hockey : nhl : david amber q&a, part i: 'my job is not to be ron jr.'",
            "section" : "sportsnet : hockey",
            "subSection" : "sportsnet : hockey : nhl",
            "contentName" : "david amber q&a, part i: 'my job is not to be ron jr.'",
            "complete90percent" : "false, // default: false"
        }

1 个答案:

答案 0 :(得分:1)

你可以用它。请记住,这最终只适用于您指定的方案。其他输入可能会导致问题。你必须自己检查一下。

// use regex to get data
$matches = [];
preg_match_all('/([A-Za-z0-9]*?)\s:\s(?:(?:\'(.*)\')|(.*)),/', $str, $matches);

// combine arrays of matches, remove slashes
array_walk($matches[2], function(&$val, $key) use ($matches) {
    if (empty($val)) {
        $val = $matches[3][$key];
    }
    $val = str_replace("\'", "'", $val);
});

// create data array
$result = array_combine($matches[1], $matches[2]);

// convert data array to json
$json = json_encode($result);


print_r($json);

输出:

{  
   "account":"rogersrmisports",
   "brand":"Sportsnet",
   "tags":"",
   "cmsid":"2912963",
   "wordCount":"3197",
   "publishDate":"July 11, 2016",
   "products":"",
   "pages":"sportsnet : hockey : nhl : david amber q&a, part i: 'my job is not to be ron jr.'",
   "section":"sportsnet : hockey",
   "subSection":"sportsnet : hockey : nhl",
   "contentName":"david amber q&a, part i: 'my job is not to be ron jr.'",
   "complete90percent":"false"
}