[英]Decoding JSON that contains Base64
I'm sending a request for a set of images to one of my API's.我正在向我的一个 API 发送一组图像的请求。 The API returns these images in a JSON format.
API 以 JSON 格式返回这些图像。 This format contains data about the resource together with a single property that represents the image in Base64.
此格式包含有关资源的数据以及表示 Base64 中图像的单个属性。
An example of the JSON being returned.返回 JSON 的示例。
{
"id": 548613,
"filename": "00548613.png",
"pictureTaken": "2020-03-30T11:38:21.003",
"isVisible": true,
"lotcode": 23,
"company": "05",
"concern": "46",
"base64": "..."
}
The correct content of the Base64 Base64的正确内容
The incorrectly parsed Base64错误解析的 Base64
This is done with the Python3 requests library.这是通过 Python3 请求库完成的。 When i receive a successful response from the API i attempt to decode the body to JSON using:
当我收到来自 API 的成功响应时,我尝试使用以下命令将正文解码为 JSON:
url = self.__url__(f"/rest/all/V1/products/{sku}/images")
headers = self.__headers__()
r = requests.get(url=url, headers=headers)
if r.status_code == 200:
return r.json()
elif r.status_code == 404:
return None
else:
raise IOError(
f"Error retrieving product '{sku}', got {r.status_code}: '{r.text}'")
Calling .json()
results in the Base64 content being messed up, some parts are not there, and some are replaced with other characters.调用 .json
.json()
会导致 Base64 内容乱七八糟,有些部分不存在,有些被其他字符替换。 I tried manually decoding the content using r.content.decode()
with the utf-8
and ascii
options to see if this was the problem after seeing this post .我尝试使用
r.content.decode()
和utf-8
和ascii
选项手动解码内容,看看这是否是看到这篇文章后的问题。 Sadly this didn't work.可悲的是,这没有奏效。 I know the response from the server is correct, it works with Postman, and calling
print(r.content)
results in a JSON document containing the valid Base64.我知道来自服务器的响应是正确的,它适用于 Postman,调用
print(r.content)
会生成包含有效 Base64 的 JSON 文档。
How would i go about de-serializing the response from the API to get the valid Base64?我将如何 go 关于反序列化来自 API 的响应以获得有效的 Base64?
import base64
import re
...
b64text = re.search(b"\"base64\": \"(?P<base>.*)\"", r.content, flags=re.MULTILINE).group("base")
decode = base64.b64decode(b64text).decode(utf-8)
Since you're saying "calling print(r.content)
results in the valid Base64", it's just a matter of decoding the base64.既然您说“调用
print(r.content)
会产生有效的 Base64”,那么只需解码 base64。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.