Tag Archives: Interface automation test

[Solved] Interface automation test: JSON parse error

1.error:
{
“title” : “Bad Request”,
“status” : 400,
“detail” : “JSON parse error: Unrecognized token ‘username’: was expecting (‘true’, ‘false’ or ‘null’); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘username’: was expecting (‘true’, ‘false’ or ‘null’)\n at [Source: (PushbackInputStream); line: 1, column: 10]”,
“path” : “/getToken”,
“message” : “error.http.400”
}
2.codes

import requests


url = 'http://10.165.153.210/getToken'
headers = {
    'Content-Type': 'application/json'
}
payload = {
    'username': 'pad_view',
    'password': '6368da1213cd4c4538128a0e9acd0288'
}
res = requests.post(url=url,method='post', data=payload, headers=headers)
print(res.text)

3. Reasons

When you request to pass parameters, the JSON string and dictionary look the same, but the background serialization format is different. Therefore, a JSON parsing error will be reported when data is passed in

4. Solutions

Convert dictionary object to JSON string

4.1 import JSON

import json

4.2 convert dictionary object to JSON string

payload = json.dumps({
    'username': 'username',
    'password': 'password'
})

4.3 complete modification code, as follows

import requests
import json  # import json


url = 'http://10.165.153.210/getToken'
headers = {
    'Content-Type': 'application/json'
}
# Convert a dictionary object into a json string, using the json.dumps() method
payload = json.dumps({
    'username': 'pad_view',
    'password': '6368da1213cd4c4538128a0e9acd0288'
})
res = requests.post(url=url,method='post', data=payload, headers=headers)
# Print the response message
print(res.text)