简体   繁体   English

使用python-requests发送带有字典数组的JSON

[英]Sending JSON with array of dicts with python-requests

I'm trying to send json containing array of dicts with requests module. 我正在尝试使用请求模块发送包含字典数组的json。 Here's sample of my code: 这是我的代码示例:

payload = {
    "arrayData": [
        {
            "key1": 1,
            "key2": 2,
            "key3": {
                "subkey": 3
            }
        }
    ]
}
r = requests.post(
    'https://httpbin.org/post',
    data = payload,
)
print(r.text)

Here's what I believe my request looks like: 我认为我的要求如下所示:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "arrayData": [
      "key1", 
      "key2", 
      "key3"
    ]
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "44", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "url": "https://httpbin.org/post"
}

The problem is arrayData at some moment turns to plain list of values. 问题是arrayData有时会变成简单的值列表。

It is crucial to my task to send that json as form but I'm out of ideas how to do that. 以表格形式发送json对我的任务至关重要,但是我不知道该怎么做。 Sending request with json=payload or with data=json.dumps(payload) doesn't do the trick because parsed data goes to "json" part but I need it in "form". 使用json = payload或data = json.dumps(payload)发送请求并不能解决问题,因为解析后的数据进入“ json”部分,但我需要使用“ form”形式。

In my example arrayData contains only one dict, but there may be several. 在我的示例中,arrayData仅包含一个字典,但可能有多个。

Turns out it was form with arrayData field and JSON content, so correct payload should be like this: 原来它是带有arrayData字段和JSON内容的表单,因此正确的有效负载应如下所示:

payload = {
"arrayData": json.dumps([{
    "key1": 1,
    "key2": 2,
    "key3": {
        "subkey": 3
        }
    }])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM