У меня неверный 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
, чтобы включить sh дополнительные "
чтобы я мог разобрать 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);