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?
-
Are you adding encoding to HTML document too?Justinas– Justinas2014-05-27 06:53:39 +00:00Commented May 27, 2014 at 6:53
-
Yes, I'm adding this: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />Noor– Noor2014-05-27 06:54:18 +00:00Commented May 27, 2014 at 6:54
-
Can you include a JSFiddle? It may be a problem in which the server sends the data.Sam P– Sam P2014-05-27 06:55:11 +00:00Commented May 27, 2014 at 6:55
-
unfortunately, I've too many dependenciesNoor– Noor2014-05-27 08:01:12 +00:00Commented May 27, 2014 at 8:01
Add a comment
|
1 Answer
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.
2 Comments
Noor
this definitely does the trick, but I'm using the json string on loads of places, i cannot manually do it
Cerbrus
@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.