分析提供的示例行时,很容易将 JSON 编码中的错误可视化。有模式,很容易恢复。
正则表达式方法
您可以使用 2 个阶段的正则表达式来修复您的字符串,第一个阶段引入缺失的双引号,第二个阶段注入逗号分隔符。
<?php
$str = '{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}';
$str = preg_replace( '/"\w+":\s"[\w\s]*/' , '$0"' , $str);
$str = preg_replace( '/""/' , '","' , $str);
echo $str;
?>
字符串操作方法
另一种方法是解构,拆分字符串,处理部分,然后再次构建对象:
<?php
$str = '{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}';
// remove '{' from the beggining of the string
$str = ltrim($str, '{');
// remove '}' from the end of the string
$str = rtrim($str, '}');
// remove the first '"' from the beggining of the string
$str = ltrim($str, '"');
// split the string in each '"'
$raw = explode('"' , $str);
// prepare an empty array to store valid properties&values
// and store in it the valid keys (removing useless keys ":")
$clean = array();
for ($i = 0; $i < count($raw); $i++) {
if ( trim( $raw[$i] ) !== ":") array_push( $clean,$raw[$i] );
}
// asumming property names are on odd keys
// and values in even keys
// we can now create a valid object...
$obj = array();
for ($i = 0; $i < count($clean); $i++) {
if ( $i % 2 === 0) $obj[ $clean[$i] ] = $clean[$i+1];
}
// and convert it back to JSON notation
$jsonObj = json_encode($obj);
echo $jsonObj;
?>
输入(无效的 json):
'{"id_content": "1"name": "Zappos 案例页面 1"id_content_type": "1}'
输出(有效的 json):
'{"id_content":"1","name":"Zappos 案例页面 1","id_content_type":" 1"}'
只有在模式始终相同的情况下,此代码才有效。否则,您将不得不将代码添加到不同的场景中。