简体   繁体   中英

Sending JSON with array of dicts with python-requests

I'm trying to send json containing array of dicts with requests module. 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.

It is crucial to my task to send that json as form but I'm out of ideas how to do that. 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".

In my example arrayData contains only one dict, but there may be several.

Turns out it was form with arrayData field and JSON content, so correct payload should be like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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