0

Suppose you have the following JSON object:

    {"name":"John Smith",
      "jsonData": "{\"comment\":\"He said \\\"It will work\\\", and we are waiting.\"}"
    }

The question is how to convert the above object to a string using say JavaScript JSON.stringify() and be able to save it in a text field in the DB and retrieve it later, parse it, and also part the inner encoded object jsonData?

The problem is faced in JavaScript and Java. For simplicity, I will reproduce the problem in JavaScript:

var jsonStr = `{"name":"John Smith",
                "jsonData": "{\\\"comment\\\":\\\"He said \\\"It will work\\\", and we are waiting.\\\"}"
               }`;
var obj = JSON.parse(jsonStr);
var comments = JSON.parse(obj.jsonData);
console.log(comments)

The above is failing with the error: Uncaught SyntaxError: Unexpected token I in JSON at position 21

And, I couldn't figure out how to include a quoted string in the inner encoded JSON string He said "It will work".

I want the solution in both Java and JavaScript.

tarekahf
  • 738
  • 1
  • 16
  • 42

1 Answers1

1

Have you considered base64 encoding the JSON string? Read more about base64 encoding objects here: Base64 encode a javascript object

  • Yes thanks a lot... I think this is a better idea. I'll work on it. In the meantime could you please point me to the solution using escape characters? – tarekahf Aug 21 '21 at 18:34