如何将Python请求的unicode输出转换为字典

问题描述 投票:0回答:2

我有以下代码

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字符组成。 我如何将其转换为所需的字典?

python
2个回答
0
投票

如果您调用的路由返回 json,只需执行以下操作:

dict_r = r.json()

dict_r 将是一个 Python 字典。

有关更多信息,请参阅请求文档:https://requests.readthedocs.io/en/latest/user/quickstart/#json-response-content


0
投票

我得到了结果

Response content is not valid JSON:
错误。您可以按如下方式检查结果:

def get_tid() -> str:
    URL = 'https://extranet-lv.bwfbadminton.com/api/vue-current-live'
    
    try:
        r = requests.post(URL, headers=headers, json={'drawCount': '0'})
        r.raise_for_status()  # Check if the request was successful
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
        return
    except Exception as err:
        print(f"Other error occurred: {err}")
        return
    
    try:
        text = r.json()  # Attempt to parse the JSON response
        print(text)
    except requests.exceptions.JSONDecodeError:
        print("Response content is not valid JSON:")
        print(r.text)  # Print the raw response text for debugging
© www.soinside.com 2019 - 2024. All rights reserved.