JS 中 json数据 与 base64、ArrayBuffer之间转换
json 字符串进行 base64 编码
javascript
function jsonToBase64(json) {
return Buffer.from(json).toString('base64');
}
base64 字符串转为 json 字符串
javascript
function base64ToJson(base64) {
try {
const binaryString = atob(base64);
const jsonString = new TextDecoder().decode(new Uint8Array(binaryString.split('').map(c => c.charCodeAt(0))));
return jsonString;
} catch (error) {
console.error('Failed to decode Base64 string:', error);
throw error;
}
}
ArrayBuffer 转换为 base64
javascript
function arrayBufferToBase64(arrayBuffer) {
return arrayBuffer.toString('base64');
}
base64 字符串转换为 ArrayBuffer
javascript
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}