以下是以无效格式存储在数据库列中的json字符串。
{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}
$variable = '{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}';所以我想在php中对它进行编码和解码,那么我可以将无效的json转换成有效的并正确地解析它的正则表达式是什么?
提前谢谢。
发布于 2017-07-27 19:16:31
很容易将JSON编码中的错误可视化,分析提供的示例代码行。有一个模式,所以它可以很容易地恢复。
REGEX方法
您可以使用两个阶段的regexp来修复字符串,第一个阶段引入缺少的双引号,第二个阶段注入coma分隔符。
<?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 Case Page1“id_content_type”:"1}‘
输出(有效的json):
'{"id_content":"1","name":"Zappos Case Page 1","id_content_type":"1"}‘
只有在模式始终相同的情况下,此代码才会起作用。否则,您将不得不将代码添加到不同的场景中。
发布于 2017-07-27 19:00:53
您可以在JS本身中使用以下命令验证json。
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}如果有效,则发送到服务器端并保存到数据库中。
对于现有数据,您无法执行任何操作。在保存到数据库之前,您可能需要使用任何在线工具(http://json.parser.online.fr/)手动进行更正。
https://stackoverflow.com/questions/45348714
复制相似问题