我通过 GitHub API 获取 README, 这里的 README 是经过 Base64 编码的,
https://api.github.com/repos/Cirru/cirru.org/readme
于是我找到了 atob
函数, 直接对 Base64 的字符串进行解析
解析之后, 我发现代码里这样一行:
IPA: /ËsɪɹÉ/
对应原先的内容是:
IPA: /ˈsɪɹə/
另外特殊字符 ➤➤
解析结果也出错了..
请问编码错误出现在哪, 怎样修复?
编码弄错了:
>>> 'IPA: /ËsɪɹÉ/'.encode('latin1').decode('utf-8')
'IPA: /ˈsɪɹə/'
问题问太快了, 在 MDN 上边很快搜到了答案...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
// Usage:
utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
似乎 GitHub 已经做了对应的处理了, 于是我只要把:
atob(str)
替换成
decodeURIComponent(escape(atob(str)))
解码就成功了...