python - Python 请求 Json 正文包含一些泰语值,需要按原样编码
问题描述
我有一些包含一些thai
值的 json。它看起来像
{
"TitleName": "คุณ",
"FirstName": "Simar"
}
我需要使用这个具有确切值的 json 主体发出 Http POST 请求。thai
我正在使用 Python 3requests
库发出请求。我试过这个
headers = {
'Content-Type': "application/json",
'Authorization': "xxx",
'cache-control': "no-cache",
'Postman-Token': "xxx"
}
response = requests.request("POST", url, json=request, headers=headers)
它将json值生成为
"TitleName": "\\u0e04\\u0e38\\u0e13",
"FirstName": "Simar"
我也试过这个
json_request = json.dumps(self.request_data,ensure_ascii=False).encode('utf8')
response = requests.request("POST", url, json=json_request, headers=headers)
它将json值生成为
"TitleName": "\xe0\xb8\x84\xe0\xb8\xb8\xe0\xb8\x93",
"FirstName": "Simar"
但我希望将 json 值生成为
"TitleName": "คุณ",
"FirstName": "Simar"
帮助将不胜感激。提前致谢。
解决方案
要在 POST 请求中保留非 ascii 字符,您需要手动序列化为 json,并显式设置content-type
标头。
data = json.dumps(my_dict, ensure_ascii=False)
r = requests.post(url, headers={'content-type': 'application/json'},
data=data.encode('utf-8'))
推荐阅读
- php - PHPMailer - 文件附件错误
- visual-studio-2017 - 无法运行 2020 年 12 月的 Visual Studio 2017 Enterprise 更新
- xcode - Xcode中是否有最大数量的子项目
- discord - 如何删除 discord.js v12 中的消息
- php - 您能否在一个查询中从同一个表中提取所有父子关系列,同时保持正确的顺序?
- python - 将单个图加载到 pytorch 几何数据对象中以进行节点分类
- jenkins - Jenkinsfile 管道选项:等效时
- asp.net - 在 Visual Studio 中从 IIS 打开网站会重新启动网站
- android - Android Kotlin:如何在片段中垂直对齐 RecyclerView
- sublimetext3 - XML 语法高亮中的嵌入式 JS