[英]php code to convert invalid json string to valid json string
如何將以下無效的json字符串轉換為php中的有效字符串,我需要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"
}
您可以使用它。 請記住,這最終僅適用於您指定的方案。 其他輸入可能導致問題。 您必須自己檢查。
// 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"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.