【问题标题】:Fix invalid JSON String using regular expression, in PHP在 PHP 中使用正则表达式修复无效的 JSON 字符串
【发布时间】:2018-01-03 01:27:29
【问题描述】:

以下是以无效格式存储在数据库列中的 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 转换为有效并正确解析它的正则表达式是什么?

提前致谢。

【问题讨论】:

  • 错误太多
  • 在将 json 字符串保存到数据库之前验证它
  • 这是我的错误,在存储到数据库之前我没有验证。
  • 你试过了吗?
  • 在下面尝试了两种方法。它对我来说很好。谢谢

标签: php json regex


【解决方案1】:

分析提供的示例行时,很容易将 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"}'


只有在模式始终相同的情况下,此代码才有效。否则,您将不得不将代码添加到不同的场景中。

【讨论】:

  • 谢谢。这很好用。是的,在我的场景中,模式是相同的。
  • 我正在寻找正则表达式。感谢您更新您的答案。
【解决方案2】:

您可以通过类似的方式验证 JS 本身中的 json。

function isJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

如果有效,则发送到服务器端并保存到数据库中。

对于现有数据,您无能为力。在保存到数据库之前,您可能需要使用任何在线工具 (http://json.parser.online.fr/) 手动进行更正。

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 2016-03-29
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多