【问题标题】:How to get a required parameter from JSON response RobotFramework如何从 JSON 响应 RobotFramework 获取所需参数
【发布时间】:2020-06-07 21:50:26
【问题描述】:

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

【问题讨论】:

  • 你能告诉我们你到目前为止所做的尝试吗?
  • 嘿,请看How to Ask a good Question - Guide。并考虑不删除已批准的编辑。请提供更多详细信息:您尝试了什么,您在哪里失败...

标签: python api automation robotframework robotframework-ide


【解决方案1】:

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

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

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

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

通过post-command 将内容发送到另一个 API 的方法:

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

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

response = r.text
print(response) 

【讨论】:

  • 希望你能看到上传的图片并帮助我
【解决方案2】:

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

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

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

${ipv4}=     Set Variable    ${as dict['interfaces'][0]['ipv4']}

【讨论】:

  • ${as dict['interfaces'][0]['ipv4']} 什么是 dict,另一个问题是如何将 ipv6 中的模式存储在变量中
  • "dict" 是 "dictionary" 的缩写,一种存储 key:value 对的变量类型; ${as dict} 就是这样一个变量,它现在在响应中保存了 ipv4 对象。在我所写的内容中,您可以使用${as dict['mode']} 获得“模式”;您也可以使用${mode}= Set Variable ${as dict['mode']} 将其存储在另一个
【解决方案3】:

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

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}

【讨论】:

  • 您能否详细说明,您的答案中使用的“请求”库到底在哪里?另外,这不是它的名字;除了已经给出的副本之外,这个答案也不是任何东西。
  • @TodorMinakov 他完成了所有步骤以使用 requests 库获取 json。他现在可以将 json 中的内容存储在一个变量中
  • 不,OP没有这么说;不,您在答案中没有使用名称不正确的请求库。是的,您的答案仍然只是另一个的副本,没有提供任何新内容。
  • @TodorMinakov 我改变了答案。这应该可以回答他的问题
猜你喜欢
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 2022-06-28
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多