0

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?

4
  • Are you adding encoding to HTML document too? Commented May 27, 2014 at 6:53
  • Yes, I'm adding this: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> Commented May 27, 2014 at 6:54
  • Can you include a JSFiddle? It may be a problem in which the server sends the data. Commented May 27, 2014 at 6:55
  • unfortunately, I've too many dependencies Commented May 27, 2014 at 8:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this definitely does the trick, but I'm using the json string on loads of places, i cannot manually do it
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.