Python 请求,返回:解析值时遇到意外字符:L. 路径

Ilu*_*r14 2 python json python-requests

我正在尝试从 The Trade Desk 的(沙盒)api 获取身份验证令牌,但我收到了 400 响应,指出:

“将 Content-Type 'application/json' 读取为 JSON 时出错:解析值时遇到意外字符:L。路径 '',第 0 行,位置 0。”

整体response.json()

{u'ErrorDetails': [{u'Reasons': [u"Error reading Content-Type 'application/json' as JSON: Unexpected character encountered while parsing value: L. Path '', line 0, position 0."], u'Property': u'TokenRequest'}], u'Message': u'The request failed validation. Please check your request and try again.'}
Run Code Online (Sandbox Code Playgroud)

我的脚本(可运行):

import requests

def get_token():

    print "Getting token"
    url = "https://apisb.thetradedesk.com/v3/authentication"

    headers = {'content-type': 'application/json'}

    data = {
              "Login":"logintest",
              "Password":"password",
              "TokenExpirationInMinutes":60
            }

    response = requests.post(url, headers=headers, data=data)

    print response.status_code
    print response.json()

    return

get_token()
Run Code Online (Sandbox Code Playgroud)

沙盒文档在这里

我相信这意味着我的headersvar 没有被正确序列化requests,这似乎是不可能的,或者没有被 The Trade Desk 正确反序列化。我已经进入了requests库,但我似乎无法破解它,正在寻找其他输入。

fer*_*rdy 6

你需要做

import json
Run Code Online (Sandbox Code Playgroud)

并将您的 dict 转换为 json:

response = requests.post(url, headers=headers, data=json.dumps(data))
Run Code Online (Sandbox Code Playgroud)

另一种方法是明确地json用作参数:

response = requests.post(url, headers=headers, json=data)
Run Code Online (Sandbox Code Playgroud)

背景:prepare_bodyrequests 方法中,字典被显式转换为 json 并且还会自动设置内容头:

if not data and json is not None:
        content_type = 'application/json'
        body = complexjson.dumps(json)
Run Code Online (Sandbox Code Playgroud)

如果您通过,data=data那么您的数据将仅进行表单编码(请参阅http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests)。如果您希望 json 成为 http 正文的内容类型,则需要明确地将其转换为 json。

您的后续问题是关于为什么不必将标头转换为 json。标头可以简单地作为字典传递到请求中。无需将其转换为 json。原因是特定于实现的。

  • 从 data=data 转移到 json-data 有帮助!谢谢! (2认同)