简体   繁体   English

JavaScript编码和解码错误

[英]JavaScript Encoding & Decoding Error

I am getting an issue with Javascript Encoding and Decoding. 我在使用Javascript编码和解码时遇到问题。 I have a json object which contains a string encoded in UTF-8 like 'R\\xc3\\xa9union' . 我有一个json对象,其中包含以UTF-8编码的字符串,例如'R\\xc3\\xa9union' To ensure that the Javascript file correctly displays the string, I'm adding an attribute charset to the script tag. 为了确保Javascript文件正确显示字符串,我将一个属性charset添加到script标签。 The json object is in countries.js . JSON对象是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 . 我包括countries.js如<script src="js/countries.js" charset="UTF-8"></script>但它仍然被显示为Ré工会代替团聚 Any suggestion? 有什么建议吗?

Use escape() combined with decodeURIComponent() : 结合使用escape()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. 现在,您说您无法在需要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: 我真的不知道一种无需使用JS重新构建JSON就可以自动执行此操作的方法,因此建议您编写一个“包装器”函数以进行实时解码:

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. 现在,还有什么可以工作,但更多的是有点冒险: JSON.stringify()整个对象,解码,使用2个功能,然后JSON.parse()一遍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM