将逗号分隔符添加到其他有效的JSON字符串中

时间:2019-01-01 02:20:48

标签: javascript

我从许多文件中读取了类似JSON的字符串,这些文件具有类似JSON的语法,但没有逗号分隔根键/值对(例如"name": "Apple Beery"而不是"name": "Apple Beery",):

var data = `{
    "name": "Apple Beery"
    "phrases": [
        "a",
        "b",
        "It's"
    ]
    "reference": 19
    "friends": [
        {
            "name": "Dog",
            "reference": 14
        },
        {
            "name": "Markus Beery",
            "reference": 30
        }
    ]
    "last": "b"
}`;

是否可以将动态逗号添加回JSON字符串,因此可以像这样解析JSON:

var data = JSON.parse(`{
    "name": "Apple Beery",
    "phrases": [
        "a",
        "b",
        "It's"
    ],
    "reference": 19,
    "friends": [
        {
            "name": "George Beery",
            "reference": 14
        },
        {
            "name": "Markus Beery",
            "reference": 30
        }
    ],
    "last": "b"
}`);

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式来匹配行中的最后一个字符(除了逗号,{[以外的任何字符),如果下一行以{开头,[",请替换为该字符再加上一个逗号。如果下一行可能还有数字,请将\d也添加到最终字符集中:

const data = `{
    "name": "Apple Beery"
    "phrases": [
        "a",
        "b",
        "It's"
    ]
    "reference": 19
    "friends": [
        {
            "name": "Dog",
            "reference": 14
        },
        {
            "name": "Markus Beery",
            "reference": 30
        }
    ]
    "last": "b"
}`;
const json = data.replace(/[^,{[](?=\n *["[{\d])/gm, '$&,');
console.log(JSON.parse(json));

图案

[^,{[](?=\n *["[{\d])

表示:

  • [^,{[]-不是逗号,{[的任何字符
  • (?=\n *["[{\d])-预告:
    • \n *-换行符,后跟任意数量的空格,和
    • ["[{\d]-除[{或数字之外的任何字符