首页 > 解决方案 > 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"

帮助将不胜感激。提前致谢。

标签: pythonjsoncharacter-encodingpython-requeststhai

解决方案


要在 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'))

推荐阅读