如何将requests返回的Unicode格式输出转换为字典?
问题描述
我编写了如下代码:
import requests headers = { 'Host': 'extranet-lv.bwfbadminton.com', 'Content-Length': '0', 'Sec-Ch-Ua': '"Chromium";v="123", "Not:A-Brand";v="8"', 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=UTF-8', 'Sec-Ch-Ua-Mobile': '?0', 'Authorization': 'Bearer 2|NaXRu9JnMpSdb8l86BkJxj6gzKJofnhmExwr8EWkQtHoattDAGimsSYhpM22a61e1crjTjfIGTKfhzxA', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.6312.122 Safari/537.36', 'Sec-Ch-Ua-Platform': '"macOS"', 'Origin': 'https://match-centre.bwfbadminton.com', 'Sec-Fetch-Site': 'same-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://match-centre.bwfbadminton.com/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 'Priority': 'u=1, i' } def get_tid() -> str: URL = f'https://extranet-lv.bwfbadminton.com/api/vue-current-live' r = requests.post(URL, headers=headers, json={'drawCount': '0'}) if r.status_code == 200: encoded_r = r.text.encode('utf-8')
期望输出格式如下:
{"results":[{"id":4746,"code":"DAC5B0C1-A817-4281-B3C6-F2F3DA65FD2B","name":"PERODUA Malaysia Masters 2024", ...}
我认为r.text的输出包含Unicode字符,请问如何将其转换为目标字典?
解决方案
不需要手动编码r.text,requests库内置了JSON响应解析方法,直接用r.json()就能将响应内容转换成Python字典,自动处理Unicode字符:
修改后的代码如下:
import requests headers = { 'Host': 'extranet-lv.bwfbadminton.com', 'Content-Length': '0', 'Sec-Ch-Ua': '"Chromium";v="123", "Not:A-Brand";v="8"', 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=UTF-8', 'Sec-Ch-Ua-Mobile': '?0', 'Authorization': 'Bearer 2|NaXRu9JnMpSdb8l86BkJxj6gzKJofnhmExwr8EWkQtHoattDAGimsSYhpM22a61e1crjTjfIGTKfhzxA', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.6312.122 Safari/537.36', 'Sec-Ch-Ua-Platform': '"macOS"', 'Origin': 'https://match-centre.bwfbadminton.com', 'Sec-Fetch-Site': 'same-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://match-centre.bwfbadminton.com/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 'Priority': 'u=1, i' } def get_tid() -> dict: URL = 'https://extranet-lv.bwfbadminton.com/api/vue-current-live' r = requests.post(URL, headers=headers, json={'drawCount': '0'}) if r.status_code == 200: # 直接解析响应为字典 response_dict = r.json() return response_dict
补充说明
r.text是响应的字符串形式,包含Unicode字符属于正常情况,r.json()会自动处理这些字符,将其转换为字典中的合法字符串。- 如果遇到JSON解析错误,可先检查并指定编码后再解析:
r.encoding = 'utf-8' response_dict = r.json() - 函数返回值类型从
str改为dict,更贴合实际返回内容的类型。
内容的提问来源于stack exchange,提问作者HJA24
相关产品推荐
相关产品推荐

