[英]How to get value from JSON list within Robot Framework?
作為 Robot Framework 驗證的一部分,我將以下數據(存儲為${response}
)作為獲取請求響應:
{
"interfaces": [
{
"name": "eth0",
"status": "ready",
"macAddress": "xx:xx:xx:xx:xx:xx",
"ipv4": {
"mode": "DHCP",
"address": "127.0.0.1",
"mask": "255.255.255.0",
},
"ipv6": {
"mode": "DISABLED",
"addresses": [],
"gateway": "",
}
}
],
"result": 0
}
我想獲取密鑰ipv4
值並將其與預定義的值進行比較。 我嘗試在HttpLibrary.HTTP
使用它,因為 Robot Framework 3.1 將不推薦使用它,所以我想使用Evaluate
。 在 Robot Framework 中可以實現嗎?
如果變量${response}
是一個響應對象——而不是一個字符串,有效載荷的內容——最直接的方法是調用它的json()
方法,它以解析字典的形式返回有效載荷:
${the data}= Evaluate ${response.json()}
另一種方法是自己用json.loads()
解析有效負載,傳遞存儲它的.content
屬性(這幾乎是.json()
在內部所做的):
${the data}= Evaluate json.loads(${response.content}) json
如果該變量${response}
是一個字符串,即實際有效負載,則只需將其傳遞給json.loads()
:
${the data}= Evaluate json.loads($response) json
現在您已將數據作為常規字典,請按正常方式進行驗證:
Should Be Equal ${the data['interfaces'][0]['ipv4']} ${your predefined dictionary}
這就是你所需要的嗎?
jsonObj = {
"interfaces": [
{
"name": "eth0",
"status": "ready",
"macAddress": "xx:xx:xx:xx:xx:xx",
"ipv4": {
"mode": "DHCP",
"address": "127.0.0.1",
"mask": "255.255.255.0",
},
"ipv6": {
"mode": "DISABLED",
"addresses": [],
"gateway": "",
}
}
],
"result": 0
}
ipv6 = jsonObj['interfaces'][0]['ipv6']
print (ipv6)
輸出:
{'mode': 'DISABLED', 'addresses': [], 'gateway': ''}
在我的情況下,我只是這樣說並且有效:
${response.json()['data'][1]['b1_YDESCRI']}
我不知道 Robot Framework,但如果你想操作 JSON,你可以使用內置的 lib json。
import json
data = json.loads(response)
ipv4 = data['interfaces'][0]['ipv4']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.