对象转化成base64-再转回对象


title: 对象转化成base64,再转回对象
date: 2024-08-01 17:54:02
tags: vue3

对象转为base64

/** 将本地对象转为base64 */
function toBase(str) {
  // 将对象转换为JSON字符串
  const jsonString = JSON.stringify(str);
  // 使用encodeURIComponent将JSON字符串转换为UTF-8的百分比编码形式
  const encodedString = encodeURIComponent(jsonString);
  // 使用btoa将百分比编码形式的字符串转换为Base64
  const base64String = btoa(encodedString);
  return base64String;
}

base64转回对象

/** 将base64转成本地对象 */
function changeBase(base64String) {
  // 使用atob将Base64字符串解码为百分比编码形式的字符串
  const encodedString = atob(base64String);
  // 使用decodeURIComponent将百分比编码形式的字符串转换回JSON字符串
  const jsonString = decodeURIComponent(encodedString);
  // 将JSON字符串解析回对象
  const obj = JSON.parse(jsonString);

  // 将数字属性转换回数字类型
  obj.classScore = obj.classScore === null ? null : Number(obj.classScore);
  obj.homeworkScore =
    obj.homeworkScore === null ? null : Number(obj.homeworkScore);
  obj.examScore = obj.examScore === null ? null : Number(obj.examScore);
  return obj;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值