1

How to escape double quotes in a string at runtime for parsing json?

Basically, I have a JSON. And when I try to parse it, I'm getting JSON parse exception because of the double-quotes. And there are many files like this. This is just an example.

JSON:

{
  "event": {
    "signUp": false,
    "info": {
      "celebity": "In an attempt to \\"test\\" purchased a table,enjoy with our who are also new \\"empty\\"  the best use of this space for our \\"always\\" enjoyment!"
    }
  }
}

I'm using couchbase SDK

JsonTranscoder trans = new JsonTranscoder();
com.couchbase.client.java.document.json.JsonObject jsonObj = trans.stringToJsonObject(json);
Aishu
  • 1,310
  • 6
  • 28
  • 52
  • 3
    Does this answer your question? [How to escape double quotes in a string for json parser in Java](https://stackoverflow.com/questions/26501523/how-to-escape-double-quotes-in-a-string-for-json-parser-in-java) – op_ Oct 21 '21 at 11:24
  • 1
    What you have is invalud JSON. It would need to be `\"` or `\\\"` instead of `\\" `. – dan1st Oct 21 '21 at 11:34
  • 2
    Looks like the backslashes are escaped after the quotes got escaped. You could attempt to replace \\ with \ (`.replace("\\\\", "\\")`), though performing mutations on raw JSON is a tricky business. (Generally the answer is, make sure that whatever is providing you the JSON is sending valid JSON.) – Ivar Oct 21 '21 at 11:35
  • 1
    Yes, the JSON you got is invalid, so the parse exception is correct. – MC Emperor Oct 21 '21 at 12:31
  • Use the [StringEscapeUtils](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html) class from Apache Commons Text – Thomas Verhoeven Oct 21 '21 at 13:01

0 Answers0