How to handle special letters(\n, \) when decoding base64 encoded json object?

Viewed 386

In JavaScript, I used follow code to make Base64 String from Json object

let inputJson  = { ... }
let objJsonStr = JSON.stringify(inputJson);
let objJsonB64 = Buffer.from(objJsonStr).toString('base64');

And in Server side, I decode it using following code.

json.loads(base64.b64decode(objJsonB64))

But I have some interesting problem. I made inputJson from input field and if input field contains special letters, then decoded value is different with original input field's value.

For example, I inputed test\ntest but I got test\\ntest on backend side. Because when I make base64 string in Frontend side, JSON.stringify() function encode as follow:

\b -> \\b 
\f -> \\f
\n -> \\n
\r -> \\r
\t -> \\t
\" -> \\"
\\ -> \\\\

So, when decoding it on backendside, result was different with original one. But when I use inputJSON with static value, all things works perfectly. Problem occurs when I make original json with special letters from input. Who ever seen similar problems?

0 Answers
Related