Javascript decode unicode backslashes in JSON

Viewed 577

I have a JSON object whose string fields can potentially contains escaped unicode characters matched by: '\\\\u' For example:

     chars\\u2078\\u2078 -> chars✨✨

I've attempted to convert using Stringify and reparsing after a replace of the extra characters in Node.Js 12:

    let s = JSON.stringify(input);
    console.log(JSON.stringify(input));
    let r = new RegExp('\\\\\\\\', 'g');
    let t = s.replace(r, '\\');
    console.log(t);
    let u = JSON.parse(t);
    console.log(u); // -> {field: 'chars⁸'}

Manually attempting to replace all unicode characters also does not work:

    let s = 'chars\\\\u2078\\\\u2078';
    console.log(s); //-> chars\\u2078\\u2078
    let r = new RegExp('\\\\(u[0-9]{4})', 'g');
    console.log(s,' ', s.replace(r, (a,b) => {return b})); //-> chars\\u2078\\u2078 chars\u2028\u2078

Is there a way to decode the escaped unicode characters such that the actual unicode value is displayed?

1 Answers

\u2078 isn't the unicode for ✨ but for ⁸. \u2728 is the unicode for ✨.

Not sure what the problem is exactly. This seems to be working fine:

let input = 'chars\\u2728\\u2728';
console.log(input);
input = JSON.stringify(input);
console.log(input);
input = input.replace(/\\\\/g, '\\');
console.log(input);
input = JSON.parse(input);
console.log(input);

Related