python requests post请求参数为多重字典的情况处理

举例说明

请求参数为:

{
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b2-1": 3,
            "b2-2": 4
        }
    },
    "c": 5
}

第一种解决办法:

声明header的Content-Type为:application/json

import requests

headers = {'Content-Type': 'application/json'}
url = "https://gz_tester.test.com/save-basicinfo"
data = {
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b2-1": 3,
            "b2-2": 4
        }
    },
    "c": 5
}
r = requests.post(url=url, json=data, headers=headers)
print(r.status_code)

运行结果如图:


image.png

第二种解决办法:

声明header的Content-Type为:application/json,
把data转换为json的字符串格式

import requests
import json

headers = {'Content-Type': 'application/json'}
url = "https://gz_tester.test.com/save-basicinfo"
data = {
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b2-1": 3,
            "b2-2": 4
        }
    },
    "c": 5
}
r = requests.post(url=url, data=json.dumps(data), headers=headers)
print(r.status_code)

运行结果如图:


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容