【问题标题】:Antislash extra double quotes with regex使用正则表达式反斜杠额外的双引号
【发布时间】: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


【解决方案1】:

这是你可以做的一个例子。

var json = `{ "key": "the log that is broken use " the character " which brake the json", "key2": "value2" }`;

var problemKey = "key";

var problemStart = json.indexOf(problemKey) + problemKey.length + 1;
var valueStart = json.indexOf("\"", problemStart) + 1;
var valueEnd = json.indexOf(",", problemStart);
var value = json.substring(valueStart, valueEnd);
valueEnd = json.lastIndexOf("\"", valueEnd);
console.log(json.substring(valueStart, valueEnd));
value = json.substring(valueStart, valueEnd);

json = json.substring(0, valueStart)
	+ json.substring(valueStart, valueEnd).replace(/"/g, "\\\"")
	+ json.substring(valueEnd);
  
console.log(json);

const obj = JSON.parse(json);

console.log(obj);

这里的(强)假设有两个

  1. 你知道有问题的键,
  2. 这些值不包含逗号。

如果您的值可以包含逗号,那么您可以通过查找下一个键来找到问题值的结尾,再次假设您确定那是什么。

正如其他人在 cmets 中所说,当然,更好的方法肯定是从源头修复 JSON。

【讨论】:

  • 谢谢,我想除了正则表达式之外别无他法
猜你喜欢
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 2020-12-04
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
相关资源
最近更新 更多