0

作为 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
        }


        And I would like to get value of key ipv4 and store in variable 
        3 library is requestlibrary collection httplibrary.http
        is there anykeyword to save this value ? please help me
4

3 回答 3

1

您可以使用请求库来访问它:

Create Session  server  http://mywebsite.com #You the ROOT URL here 
${response}=  Get Request  server  #You put the URI here
${var_dict}=    Evaluate     json.loads("""${response.content}""")    json
${ipv4}=    Set Variable    ${var_dict}[interfaces][ipv4]

这会将来自 ipv4 的所有密钥存储在变量中${ipv4}

于 2020-02-25T15:15:15.063 回答
1

您得到的响应是一个字符串,使用 python 的标准json库将其转换为 dict:

${as dict}=    Evaluate    json.loads("""${response}""")    json

现在您可以在 Robot Framework 中将其作为普通字典使用:

${ipv4}=     Set Variable    ${as dict['interfaces'][0]['ipv4']}
于 2020-02-24T18:55:15.190 回答
1

您可以使用给定的代码获取和存储值:

def get_activation_code():
    print(dict["data"]["user"]["activationCode"])
    return dict["data"]["user"]["activationCode"]

如果您提供有关“发送到另一个 API”任务的更多信息,我也可以在那里为您提供帮助,但此方法将提供activationCode. dict指的是您所说的作为响应的给定字典。

当您已经从某个地方得到响应时,我猜您已经导入了requests- 库?

一种将某些东西发送到另一个 API 的方法是通过post-command:

r = requests.post(url = the_url_of_the_target_api, data = get_activation_code())  

然后,您可以通过以下方式捕获响应:

response = r.text
print(response) 
于 2020-02-24T09:43:33.243 回答