I have a string [{"Id":"1","msg":""Lorem Ipsum""}]
in which I need to just escape the quotes inside the quotes like this [{"Id":"1","msg":"\"Lorem Ipsum\""}]
. I don't have access to generator code to modify, so I'm looking for a regex solution or efficient Java solution.
I tried selecting matches with \"[^\"]*?(\"*)[^\"]*?\"
which is of no use. Any help is really appreciated. Thanks in advance.
Note that it isn't guaranteed that the pattern is always two double quotes together, it can be something like this too "Lorem "Ipsum" test"
, which should become "Lorem \"Ipsum\" test"
.
PS: I've already looked at Regular expression to escape double quotes within double quotes
A finite automaton - the theoretical equivalent of a regex - can't parse recursive structures. Since you can have inner quotes, and possible inner-inner quotes, your problem can't be solved using a regex.
Although modern regex engines can overcome this problem with several extensions, don't waste your time on hunting quotes-within-quotes. You'll soon find out that you're actually building a full blown JSON parser.
As @johnchen902 stated, even a turing-machine powered parser can not handle ambiguities - so you better not try to suggest a fix to the broken JSON.
The given string is not a valid JSON. It's probably created using string concatenation, which is generally a bad idea because it does not escape correctly. You should use a JSON library that can build JSON from a Java data structure, like gson. Create a list of Objects, add an Object-to-Object dictionary to it, and let the library do the escaping and conversions.
If you have received the String from an external source, it's perfectly legitimate to ask for a valid json you can work with. I guess that the creator stitched Strings together, which is the wrong way to build a structured language. Ask the original creator to use a standard library for creating JSONs, or at least use a validator. All modern programming languages offer these mechanisms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With