【问题标题】:Remove quotes inside quotes with regular expression使用正则表达式删除引号内的引号
【发布时间】:2013-01-13 02:17:41
【问题描述】:

我有一个 json 文件,它的值中有很多双引号。 json文件差不多有27000条记录。

我想删除或替换值中的双引号,否则它不会被接受为一个好的 json 文件。我该怎么做?

问题是值中有一个双引号的记录,但也有其中多个引号的记录。

除了替换或删除引号外,还可以删除整个键和值。反正我不会用。这样做更容易吗?

这里是 json 文件中 1 条记录的示例:

 {
  "adlibJSON": {
    "recordList": {
      "record": [
        {
          "@attributes": {
            "priref": "4372",
            "created": "2011-12-09T23:09:57",
            "modification": "2012-08-11T17:07:51",
            "selected": "False"
          },
          "acquisition.date": [
            "1954"
          ],
          "documentation.title": [
            "A lot of text with a lot of extra double quotes like "this" and "this""
          ] ... ...

问题在于键的值:document.title。 我有 sublime text 2,我用它来查找和替换。

【问题讨论】:

  • 我会非常努力地回到源头并修复创建 JSON 的任何内容,而不是尝试修复损坏的数据。
  • 是的,它来自我无法操作的服务器
  • 如果你能找到一种方法来定位值本身(例如 [...] 中的所有内容),你可以去掉 all 引号,然后将引号放回外面。但如果你能做到这一点,你也可以删除该值。

标签: javascript regex json


【解决方案1】:

我认为你不能因为it's not a regular language

您可能会遇到与parsing HTML with regex 类似的麻烦。

我认为你必须自己编写(或者如果你非常幸运的话,可以找到)某种解析器......

【讨论】:

    【解决方案2】:

    有一种方法,但为了做到这一点,您必须确保您可以对您的数据进行以下假设:

    • “documentation.title”在您的数据中只能出现一次,当它用作键时。
    • “documentation.title”引用的数组值应该只有一个元素。
    • 字符“]”不应出现在值中。

    然后您将按照以下步骤操作:

    /* find first index of "[" after "documentation.title" */
    n = s.indexOf("[", s.indexOf('"documentation.title"'));
    
    /* Find index of closing "]" */
    n2 = s.indexOf("]", n);
    
    /* Get the substring enclosed by these indexes */
    x = s.substr(n+1, n2-n-1);
    
    /* Remove every double quotes in this string and rebuild the original string with the corrected value. */
    s.substr(0, n) + '["' + x.replace(/"/g, "") + '"]' + s.substr(n2+1);
    

    编辑:如果您对保留更正值本身不感兴趣,则可以将其替换为空字符串。

    【讨论】:

      【解决方案3】:

      试试这个:

      json.replace(/(^\s*|:\s*)"/gm, '$1[sentinel]')
          .replace(/"(,?\s*$|:)/gm, '[sentinel]$1')
          .replace(/"/g, '\\"').replace(/\[sentinel\]/g, '"');
      

      在这里演示:http://jsfiddle.net/D83FD/

      这不是一个完美的解决方案;数据的格式可能会破坏正则表达式。试试看它是否适用于更大的数据集。

      本质上,我们正在查找开始引号并将其替换为占位符值,查找结束引号并将其替换为占位符,反斜杠转义所有剩余引号,然后再次将占位符替换为引号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多