现在我正在用python编程API,我有以下问题:我必须POST以下JSON到一个url:
prescription = {
"Name": “file_name", # This is a string
"Body" : "xxx",# (File in base64 format)
"ParentId" : "xxxxxxxxxxxxxxxxxx", # This is a string
"ContentType" : "xxxxx/xxx" # This is a string
}
但是当我尝试做以下请求时:
requests.post(url, prescription)
我得到以下错误:
TypeError: Object of type bytes is not JSON serializable
我怎么能使张贴JSON的请求?这可能吗?
谢谢你的帮助。
编辑:使用
"Body" : "xxx.decode("utf-8")"
工作了,谢谢你的帮助
您可以这样做:
import base64
import requests
with open("your/file", "rb") as file:
b64_file_content= base64.b64encode(file.read())
prescription = {
"Name": "file_name", # This is a string
"Body": b64_file_content.decode("ascii"), # (File in base64 format)
"ParentId": "xxxxxxxxxxxxxxxxxx", # This is a string
"ContentType": "xxxxx/xxx", # This is a string
}
requests.post("https://somewhere.world", prescription)