在以下三个测试用例中获取Requests1,Get Requests2和Get Requests3。我尝试以三种不同的方式获取/ RestResponse / result节点值,但它显示相同的错误
*** Settings ***
Library Collections
Library OperatingSystem
Library HttpLibrary.HTTP
Library RequestsLibrary
*** Test Cases ***
Get Requests1
# create a HTTP session to a server
Create Session countryname http://services.groupkt.com
# store response
${resp}= Get Request countryname /country/get/all
log ${resp.content}
# ${resp.content} display entire json response, now tring to get node value of /RestResponse/result
${getResponseJson} Get Json Value ${resp} /RestResponse/result
# shows error TypeError: expected string or buffer
log ${getResponseJson.content}
Get Requests2
# create a HTTP session to a server
Create Session countryname http://services.groupkt.com
# store response
${resp}= Get Request countryname /country/get/all
log ${resp.content}
# ${resp.content} display entire json response, now tring to get node value of /RestResponse/result
${responseContent}= to json ${resp.content}
# shows error TypeError: expected string or buffer
${getResponseJson} Get Json Value ${responseContent} /RestResponse/result
log ${getResponseJson.content}
Get Requests3
# create a HTTP session to a server
Create Session countryname http://services.groupkt.com
# store response
${resp}= Get Request countryname /country/get/all
log ${resp.content}
# ${resp.content} display entire json response,parse json
${data} Parse Json ${resp}
# shows error TypeError: expected string or buffer
${getResponseJson} Get Json Value ${resp} /RestResponse/result
{
"RestResponse": {
"messages": [
"Total [249] records found."
],
"result": [
{
"name": "Afghanistan",
"alpha2_code": "AF",
"alpha3_code": "AFG"
},
{
"name": "\ufffd\ufffdland Islands",
"alpha2_code": "AX",
"alpha3_code": "ALA"
},
{
"name": "Albania",
"alpha2_code": "AL",
"alpha3_code": "ALB"
},
{
"name": "Algeria",
"alpha2_code": "DZ",
"alpha3_code": "DZA"
}
]
}
}
答案 0 :(得分:2)
您需要从JSON调用Get Json Value
,而不是从请求对象调用。在您的代码中,${resp}
是一个对象,其中包含JSON数据以及json解析器不知道的其他内容。
${getResponseJson} Get Json Value ${resp.content} /RestResponse/result
${resp}
是一个python对象。它有json数据,但它也有HTTP返回码和其他信息。您无法将其传递给任何接受JSON的内容。
${resp.content}
是HTTP响应的主体。就像你在评论中写的那样,这是JSON数据。任何接受JSON数据的关键字都应该接受这个。
${resp.json}
是响应转换为python对象的JSON字符串。它不再是JSON,它是一个python字典。您无法将此传递给任何需要JSON的函数。但是,您可以将其视为普通的python词典。
运行代码后,${getResponseJson}
将拥有您期望的数据。它是一个unicode字符串,unicode字符串不具有content
属性。