【发布时间】:2020-07-19 19:34:09
【问题描述】:
我要解析的字符串中有一个不正确的 JSON。不正确的是里面有双引号字符。
JSON 不正确
{ "key": "the log that is broken use the character " which brake the json", "key2": "value2" }
正确的 JSON
{ "key": "the log that is broken use the character \" which brake the json", "key2": "value2" }
是否有任何正则表达式可以与 replace 一起使用,以反击额外的 ",以便我可以解析 JSON?
const json = `{ "key": "the log that is broken use the character " which brake the json", "key2": "value2" }`;
// Do the regex and the replace ...
const obj = JSON.parse(json);
console.log(obj);
我自己尝试了多个正则表达式,但无法使其工作。另外,如果您刚刚获得领先优势,我会亲自尝试一下。
谢谢
编辑:
这是我编写的工作解决方案。有点多如果你问我,我会很感激更好的解决方案:
const json = `{ "key": "the log that is broken use the character " which brake the json", "key2": "value2" }`;
console.log(json);
// Get all occurences of the troubled strings
const [
_,
...results
] = /(?:\: "(?:(.*)*)",)|(?:\: "(?:(.*)*)" )/.exec(json);
let mutatedJson = json;
// For each occurence, replace the extra double quotes, then apply it on the main string
results.slice(0, results.length - 1).forEach((x) => {
const oldVal = x;
// Take the string without the first and last double quotes and backslash remaining quotes
const newVal = x.replace('"', "\\\"");
// Insert the clean data in
mutatedJson = mutatedJson.replace(oldVal, newVal);
});
const obj = JSON.parse(mutatedJson);
console.log(obj);
【问题讨论】:
-
这很大程度上取决于你对这个 JSON 结构的了解。您确定哪些键包含错误吗?您知道它们是否也可以包含逗号(否则您可以将其用作分隔符)。因为在没有先验知识的情况下,使用正则表达式解析通用的类 JSON 结构的可能性很小。
-
是的,我知道键和结构。我知道 JSON 内部的唯一问题是键 X 后面的值中有额外的双引号。
-
出于好奇...损坏的 JSON 是由同一个应用程序生成的吗?因为修复它可能更容易、更可靠。
-
阿尔瓦罗说的就是我的想法。另外,您可能会遇到许多其他可能导致问题的字符。从源头上修复它是最好的方法。
-
前段时间在一个应用程序中生成了损坏的 JSON,现在我们要处理数据... PS:我们有 To of data。经典现实生活工作问题^^
标签: javascript node.js json regex