Home > Back-end >  Keeping escaped unicode caracters
Keeping escaped unicode caracters

Time:12-13

I have an input JSON like this:

{"source":"Subject: NEED: 11/5 BNA-MSL \u2013 1200L Departure - 1 Pax"}

I read it with JSON.parse and it reads the \u2013 as , which is fine for display in my app.

However, I need to export again the same JSON, to send it down to some other app. I want to keep the same format and have back the \u2013 into the JSON. I am doing JSON.stringify, but it keeps the in the output.

Any idea what I could do to keep the \u syntax?

CodePudding user response:

Using a replacer function in a JSON.stringify call didn't work - strings returned from the replacer with an escaped backslash produce a double backslash in output, and a single backslashed character is unescaped in output if possible.

Simply re-escaping the stringify result has potential:

const obj = {"source":"Subject: NEED: 11/5 BNA-MSL \u2013 1200L Departure - 1 Pax"}
console.log("  stringify:  ", JSON.stringify( obj));
console.log("& replaceAll: ", JSON.stringify(obj).replaceAll('\u2013', '\\u2013'));

using more complex string modifications as necessary.

However this looks very like an X solution to an X-Y problem. Better might be to fix the downstream parsing to handle JSON text as JSON text and not try to use it in raw form - particularly given that JSON text in encoded in utf-8 and can handle non-ASCII characters without special treatment.

  • Related