如何使用json.dumps()转换36位UUID为JSON且不增加字符长度?
问题:POST UUID格式参数时触发长度与格式校验错误
我需要向指定URL POST包含36位UUID格式merchant_id及其他参数的JSON数据,但使用json.dumps()单独转换merchant_id后,字符串首尾新增了引号,长度从36位变为38位,触发接口参数校验错误,提示merchant_id长度不能超过36位且需为有效UUID。
原代码
merchant_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' merchand_id_json = json.dumps(merchant_id) # 检查转换前后的长度 print('len merchant_id before json is', len(merchant_id)) print('len merchand_id after json is', len(merchand_id_json)) # 设置请求头 request_header = { 'accept': 'application/json', 'content_type': 'application/json', } # 发送请求 res = requests.post( url=request_url, data= { "merchant_id": merchand_id_json, }, headers=request_header) # 打印响应 print('res =', res) print('res.text =', res.text)
终端输出
len merchant_id before json is 36 len merchand_id after json is 38 res = <Response [200]> res.text = {"data":[],"errors":{"code":-9,"message":"The input params invalid, validation error.","validations":[{"merchant_id":"The merchant id may not be greater than 36 characters."},{"merchant_id":"string is not a valid uuid."}]}}
问题原因
你犯了重复序列化的错误:
json.dumps(merchant_id)会把单个字符串转成带双引号的JSON字符串(比如原UUIDxxxx-xxxx-...会变成"xxxx-xxxx-...",长度增加2)- 把这个带引号的字符串放到
data字典中发送时,requests默认会按表单格式编码,或者即使你指定了JSON头,也会把这个带引号的字符串作为merchant_id的原始值传递,导致接口收到的是带引号的38位字符串,既不符合长度要求,也不是有效的UUID格式。
另外原请求头的content_type键名错误,HTTP标准头字段是Content-Type(大小写敏感),写错会导致接口无法正确识别请求格式。
解决方案
直接使用requests.post的json参数,它会自动帮你完成整个参数字典的JSON序列化,无需手动调用json.dumps(),同时会自动设置正确的Content-Type头。
修正后的代码
import requests merchant_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # 可选:如果接口明确要求Accept头,可以保留,否则可以省略 request_header = { 'Accept': 'application/json', } # 使用json参数传入原始字典,requests自动处理序列化 res = requests.post( url=request_url, json={ "merchant_id": merchant_id, # 其他参数直接添加到这个字典中即可 }, headers=request_header ) print('res =', res) print('res.text =', res.text)
补充说明
如果一定要使用data参数,需要对整个参数字典进行序列化,而不是单独序列化某个字段:
import json import requests merchant_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' request_header = { 'Accept': 'application/json', 'Content-Type': 'application/json', } # 序列化整个参数字典 payload = json.dumps({ "merchant_id": merchant_id, # 其他参数 }) res = requests.post( url=request_url, data=payload, headers=request_header )
内容的提问来源于stack exchange,提问作者cosmoscoder
相关产品推荐
相关产品推荐

