As Brasofilo said in the comments, the ideal is to prevent this wrong string from entering JSON first. Dealing with the problem after the fact is much harder...
If your JSON has exactly this format, just take everything inside the string and make a replace:
var string = '{"text": "Olha "eu" aqui"}';
var prefixo = '{"text": "';
var sufixo = '"}';
var conteudo = string.substring(prefixo.length, string.length-sufixo.length);
var novaString = prefixo + conteudo.replace(/"/g, '\\"') + sufixo;
If not, you are in trouble... How to interpret the string below?
{"text":"b","c":"d"}
- Key:
text
, value: b
; key: c
, value d
? or:
- Key:
text
, value: b","c":"d
?
That is: the only solution correct is to address the problem before the string ends up in JSON. If you have for example a legacy file in which - for any bug - the format got wrong this way, you can even use an automated process to help you fix, but you have to review it by hand... Now, if it is an existing code that is generating this type of string, this code is bug and you should fix it in the source - and not apply a "band-aid"...
Where does this string come from?
– brasofilo
Where this Json is being formatted, I agree with @brasofilo, the error ta ai ?
– user6026
This is my way of saving the settings, using string-like json in localStorage in an application of mine. I’m afraid the user put a quote and give error in the code
– Iago Bruno
The previous version of my app did not prevent it, but there was no error, now with the migration I will do it may be that in the settings have this quote
– Iago Bruno
Classic XY problem :D
– brasofilo