接口请求报错json格式问题

报错代码

import requests

url = "http://*********/admin/v1.0/task/add"

payload  = {
    "alarmType": "2",
    "departmentId": 1382562817882931211,
    "taskReceive": "137709943148954820",
    "remark": "",
    "selectDoPolicyDate": 0,
    "finsihFirishPolicyDate": 2
}
headers = {
   'token': '3683c55b1f40410aacae864c9ad06e76',
   'User-Agent': 'apifox/1.0.0 (https://www.apifox.cn)',
   'Content-Type': 'application/json',
}

response = requests.post(url, headers=headers, data =payload)
print(response.text.encode('utf8'))

报错信息

b'{"code":500,"message":"JSON parse error: Unrecognized token \'alarmType\': was expecting (JSON String, Number, Array, Object or token \'null\', \'true\' or \'false\'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token \'alarmType\': was expecting (JSON String, Number, Array, Object or token \'null\', \'true\' or \'false\')\\n at [Source: (PushbackInputStream); line: 1, column: 11]"}'

接口工具测试没有问题

解决办法1:

首先安装demjson

pip install demjson

导入demjson包,然后请求时对参数进行格式化

import requests
import demjson

url = "http://********/admin/v1.0/task/add"

payload  = {
    "alarmType": "2",
    "departmentId": 1382562817882931211,
    "taskReceive": "137709943148954820",
    "remark": "",
    "selectDoPolicyDate": 0,
    "finsihFirishPolicyDate": 2
}
headers = {
   'token': '3683c55b1f40410aacae864c9ad06e76',
   'User-Agent': 'apifox/1.0.0 (https://www.apifox.cn)',
   'Content-Type': 'application/json',
}

response = requests.post(url, headers=headers, data =demjson.encode(payload))
print(response.text.encode('utf8'))

返回结果

b'{"code":0,"message":"success"}'

解决办法2:

导入json包,进行json格式转换

import requests
import json

url = "http://********/admin/v1.0/task/add"

payload  = {
    "alarmType": "2",
    "departmentId": 1382562817882931211,
    "taskReceive": "137709943148954820",
    "remark": "",
    "selectDoPolicyDate": 0,
    "finsihFirishPolicyDate": 2
}
headers = {
   'token': '3683c55b1f40410aacae864c9ad06e76',
   'User-Agent': 'apifox/1.0.0 (https://www.apifox.cn)',
   'Content-Type': 'application/json',
}

response = requests.post(url, headers=headers, data =json.dumps(payload))

print(response.json())
#print(response.text.encode('utf8'))

返回结果

{'code': 0, 'message': 'success'}
posted @ 2021-05-07 19:31  Harry_666  阅读(1054)  评论(3编辑  收藏  举报