JS 二进制流转换为JSON对象

 fetch("/api/api/AuthenticationLogin/getQuickResponseCode", {
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          apiId: "e53f2682fe6fd77c5fd25841ec1170ef",
          apiSecret: "abe93f28d5c74b0ea2664f9869946d79",
          apiType: "channel",
          loginUUID: "6f2ab5a8df5b4259a6e8e2c8644ea8fd",
        }),
      })
        .then((res) => {
          return res.blob();
        })
        .then((res) => {
          console.log("==================>");
          console.log(res);
          let read = new FileReader()
          // 通过文件流对象将文件流转换为字符串,再通过JSON.parse 转换为json对象
          read.readAsText(res,'utf-8')
          read.onload = (data)=>{
            console.log(JSON.parse(data.currentTarget.result));
          }
          this.QRCode = URL.createObjectURL(res);
          // 轮询
          this.poll();
        });
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想要在前端二进制转换JSON 并下载为文件,可以使用以下示例代码: ```javascript function downloadJsonFile(data, fileName) { const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/json' }); if (navigator.msSaveBlob) { // For IE and Edge navigator.msSaveBlob(blob, fileName); } else { const link = document.createElement('a'); const url = URL.createObjectURL(blob); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); setTimeout(() => { document.body.removeChild(link); URL.revokeObjectURL(url); }, 0); } } // Example usage: const jsonData = ... // Your JSON data const fileName = 'example.json'; downloadJsonFile(jsonData, fileName); ``` 在上面的示例代码中,`downloadJsonFile` 函数接收 JSON 数据和文件名作为参数。它首先将 JSON 数据转换为字符串,并创建一个 Blob 对象,将字符串和 MIME 类型 `'application/json'` 传递给它。然后,根据浏览器支持情况,通过不同的方式来触发文件下载。 对于 IE 和 Edge 浏览器,使用 `navigator.msSaveBlob` 方法来保存 Blob 对象。对于其他现代浏览器,使用 URL.createObjectURL 创建一个临时的下载链接,并将其附加到一个 `<a>` 元素上。然后,模拟点击这个链接来触发文件下载。最后,在下载完后,移除临时链接并释放资源。 请确保你已经将正确的 JSON 数据传递给 `downloadJsonFile` 函数,并提供了正确的文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值