如何使用 JSON 响应保存文件

huangapple go评论56阅读模式
英文:

How to save the file with a json response

问题

响应得到的是一个类似以下内容的JSON:

{'additionalErrors': None,
 'data': {'contentType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'file': 'UEsDBBQACAAIAAAAAAAAAAAAAAAAAAAAAAATAAAAeGwvdGhlbWUvdGhlbWUxLnhtbOyZz2/bNhT...
          (还有大约11k个字符)
          ...hsL3N0eWxlcy54bWxQSwUGAAAAAAsACwDGAgAASB4AAAAA',
          'name': 'export-data.xlsx'},
 'error': False,
 'errorText': ''}

有可能通过这些数据将文件下载到计算机上吗?

我不知道如何解决这个问题。

英文:

response gets a json of something like this:

{'additionalErrors': None,
 'data': {'contentType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'file': 'UEsDBBQACAAIAAAAAAAAAAAAAAAAAAAAAAATAAAAeGwvdGhlbWUvdGhlbWUxLnhtbOyZz2/bNhT...
          (there are still about 11k characters)
          ...hsL3N0eWxlcy54bWxQSwUGAAAAAAsACwDGAgAASB4AAAAA',
          'name': 'export-data.xlsx'},
 'error': False,
 'errorText': ''}

Is it possible, having this data, to download the file to a computer?

I don't know how to solve this problem

答案1

得分: 1

你在收到这个回复时已经下载了文件,它只是以Base64格式进行编码。要解码它,你可以按照以下步骤进行操作:

import base64

resp = ...  # 获取你的JSON响应

decoded = base64.b64decode(resp["data"]["file"])
with open("/some/path", "wb") as f:
    f.write(decoded)
英文:

You already downloaded the file when you get this response, it's just encoded in base64 format. To decode it, you can do this:

import base64

resp = ... # get your JSON response

decoded = base64.b64decode(resp["data"]["file"])
with open("/some/path", "wb") as f:
    f.write(decoded)

huangapple
  • 本文由 发表于 2023年7月27日 17:30:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定