【问题标题】:Python Requests, getting back: Unexpected character encountered while parsing value: L. PathPython请求,返回:解析值时遇到意外字符:L.路径
【发布时间】:2016-03-07 05:04:18
【问题描述】:

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

“将 Content-Type 'application/json' 读取为 JSON 时出错:意外 解析值时遇到的字符:L. Path '', line 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.'}

我的脚本(可运行):

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()

Sandbox docs here

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

【问题讨论】:

  • 数据需要拨打json.dump吗?
  • 宾果游戏,就是这样,让它工作。你能解释一下吗?
  • data 本身就是一个python字典;它不是json格式。调用 json.dumps 会将其转换为 json。
  • 我在下面回答了,但是 john 比我快很多。
  • 谢谢大家,非常感谢。我会接受你的回答@ferdy

标签: python json python-requests


【解决方案1】:

你需要做的

import json

并将您的 dict 转换为 json:

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

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

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

背景:在请求的prepare_body方法中,字典被显式转换为json,并且内容头也被自动设置:

if not data and json is not None:
        content_type = 'application/json'
        body = complexjson.dumps(json)

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

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

【讨论】:

  • 作为后续,我为什么不用将headers转换成json?
  • 我已经扩展了我的答案,使其更加冗长。 HTH
  • 从 data=data 转移到 json-data 有帮助!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-31
相关资源
最近更新 更多