Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object serialisation with toSource() converts special chars to hex code - how to reverse?

If I'm converting a simple JavaScript object to a string, all special chars will be converted to hex code.

function O() {
    this.name = "<üäö!";
}
var myObject = new O();
console.log(myObject.toSource());

Result:

{name:"<\xFC\xE4\xF6!"}

How would I avoid this or convert all hex chars back to utf8 chars?

like image 891
dan Avatar asked Feb 07 '26 15:02

dan


1 Answers

If you use Crockford's json2.js, you completely avoid this issue.

console.log(JSON.stringify(myObject));

outputs

{"name":"<üäö!"}

You can then send this string, e.g. using an XMLHttpRequest (in that case, don't forget to use encodeURIComponent).

like image 165
Marcel Korpel Avatar answered Feb 09 '26 07:02

Marcel Korpel