简体   繁体   中英

why does python requests.post accept json for data but not a dictionary

The documentation seems to indicate I can pass 'data=' as a dictionary, but I get an error unless I use json.dumps()

options = {
    "deviceId":["4d51de64-2235-a465-3aee-5ec495b5b250"],
    "serviceName":"software_manager",
    "serviceVersion":"1.0",
    "actionName":"Dump Log Files" }

res = requests.post( req, data=json.dumps(options), auth=cred) 

If I try to pass options as a dictionary it fails.

res = requests.post( req, data=options, auth=cred) 

data=json.dumps(options) # This works
data=options             # this fails

Why? Am I missing something in the docs?

The data parameter of requests.post() either accepts data as form-encoded (if you pass it a dict ) or as a raw string (which is why json.dumps(options) works).

In order to pass in a non-encoded dictionary, you should use the json parameter of .post() .

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