【问题标题】:Loading JSON using Python Requests wrong type使用 Python 请求错误类型加载 JSON
【发布时间】:2016-02-22 17:04:38
【问题描述】:

我正在尝试使用 Python 将一些数据加载到 ML。这可以正常工作,但在 ML 中类型设置为“T”而不是“J”。 我想解决这个问题。标题设置似乎只是为了展示所以我该怎么做?

# Sending data
data = {'meting': '477', 'bericht': '473', 'plant': '01'}
url = 'http://server:8000/v1/documents?database=thijsPlantjes&extension=json'
headers = {'Content-Type': 'application/json'}
r = requests.post(url, json = json.dumps(data), auth=HTTPDigestAuth('plantje', 'password'), headers = headers) 

【问题讨论】:

  • json 关键字参数的全部意义在于它为您执行 JSON 序列化,包括将 Content-Type 标头设置为 application/json

标签: python json python-requests marklogic


【解决方案1】:

如果你使用json参数,requests会为你序列化,所以你不需要自己json.dumps

它还会为你设置内容类型;您可以删除 headers 关键字参数。

r = requests.post(url, json=data, auth=HTTPDigestAuth('plantje', 'password'))

根据requests documentation

不用自己编码dict,也可以直接传 使用 json 参数(在 2.4.2 版中添加),它将是 自动编码:

【讨论】:

  • 它还设置了Content-Type标头,这里的headers参数完全是多余的。
  • @MartijnPieters,感谢您提供的信息。我相应地更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多