首页 > 解决方案 > 修复无效的 JSON

问题描述

我有一个巨大的文件,不幸的是包含无效的 JSON。它看起来像数组列表,没有用逗号分隔:

[{
    "key": "value"
}]
[
    [{
            "key": "value",
            "obj": {}
        },
        {}
    ]
]
[{
    "key": "value",
    "obj": {}
}]

每个方括号对内的内容本身似乎是一个有效的 JSON

问题是如何使用“搜索和替换”快速修复这个 JSON?(或任何其他方法)

尝试了许多组合,包括将“ ][ ”替换为“ ],[ ”,并用另一个方括号对包装整个文件,使其成为数组数组。每次它给我无效的JSON。

请帮忙。

标签: phparraysjsonvalidation

解决方案


You can replace the closing brackets with '],' and wrap the entire string in brackets.

This snippet illustrates the method with the supplied sample data by applying the algorithm and then calling eval on the resulting string.

let jsonString = `[{
    "key": "value"
}]
[
    [{
            "key": "value",
            "obj": {}
        },
        {}
    ]
]
[{
    "key": "value",
    "obj": {}
}]`;

jsonString = jsonString.replace( /]/g, '],' );
jsonString = '[' + jsonString + ']';

myObject = eval( jsonString );

console.log( typeof myObject);
console.log( myObject.length );
console.log( myObject );


推荐阅读