Memo

20240113 bjnlsba5

JSON 与 Base64 互转 `typescript // Encode { const obj = {"Hello": "World"} const bytes = new TextEncoder().encode(JSON.stringify(obj)); const binStr = String.fromCharCode(...bytes); const base64Str...

JSON 与 Base64 互转

// Encode

{
 const obj = {"Hello": "World"}

 const bytes = new TextEncoder().encode(JSON.stringify(obj));
 const binStr = String.fromCharCode(...bytes);
 const base64Str = btoa(binStr);

 console.log('base64', base64Str);
}

// Decode

{
 const base64Str = 'eyJIZWxsbyI6IldvcmxkIn0=';

 const binStr = atob(base64Str);
 const bytes = Uint8Array.from(binStr, (m) => m.codePointAt(0)!);
 const jsonStr = new TextDecoder().decode(bytes);

 const obj = JSON.parse(jsonStr);

 console.log('obj', obj);
}

btoa 函数需要传入一个二进制字符串,而 Unicode 字符串可能会出现一个字符占用多个字节,会因为字符“太宽”导致函数执行失败。

在线:json <-> base64 MDN:btoa() global functionx