I am getting an issue with Javascript Encoding and Decoding. I have a json object which contains a string encoded in UTF-8 like 'R\xc3\xa9union'
. To ensure that the Javascript file correctly displays the string, I'm adding an attribute charset to the script tag. The json object is in countries.js
. I'm including countries.js as <script src="js/countries.js" charset="UTF-8"></script>
and yet it is still being displayed as Réunion instead of Réunion. Any suggestion?
Asked
Active
Viewed 2,234 times
0

Noor
- 19,638
- 38
- 136
- 254
-
Are you adding encoding to HTML document too? – Justinas May 27 '14 at 06:53
-
Yes, I'm adding this: – Noor May 27 '14 at 06:54
-
Can you include a JSFiddle? It may be a problem in which the server sends the data. – Sam P May 27 '14 at 06:55
-
unfortunately, I've too many dependencies – Noor May 27 '14 at 08:01
1 Answers
1
Use escape()
combined with decodeURIComponent()
:
decodeURIComponent(escape('R\xc3\xa9union'));
That should do the trick:
escape('R\xc3\xa9union'); // "R%C3%A9union"
decodeURIComponent("R%C3%A9union"); // "Réunion"
Now, you said you couldn't do this manually for all the places you need strings from the JSON. I really don't know a way to automate this without re-building the JSON with JS, so I'd suggest writing a little "wrapper" function to decode on the fly:
function dc(str){
return decodeURIComponent(escape(str));
}
You can then decode the required strings with minimal effort:
var myString = dc(myJson["some"]["value"]);
Now, what else could work, but is a little more risky: JSON.stringify()
the entire object, decode that using the 2 functions, then JSON.parse()
it again.

Cerbrus
- 70,800
- 18
- 132
- 147
-
this definitely does the trick, but I'm using the json string on loads of places, i cannot manually do it – Noor May 27 '14 at 06:59
-
@Noor: As far as I know, there is no "automatic" way of letting JavaScript know how to interpret those strings. I've added a little suggestion on how to do it semi-automated. – Cerbrus May 27 '14 at 07:08