【问题标题】:How to get value from JSON list within Robot Framework?如何从 Robot Framework 中的 JSON 列表中获取价值?
【发布时间】:2019-07-22 15:25:42
【问题描述】:

作为 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 中是否有可能?

【问题讨论】:

标签: python json robotframework


【解决方案1】:

如果变量 ${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}

【讨论】:

    【解决方案2】:

    这就是你所需要的吗?

    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': ''}
    

    【讨论】:

      【解决方案3】:

      就我而言,我只是这样说并且有效:

      ${response.json()['data'][1]['b1_YDESCRI']}
      

      【讨论】:

        【解决方案4】:

        我不知道Robot Framework,但是如果你想操作JSON,你可以使用内置的lib json。

        import json
        
        data = json.loads(response)
        
        ipv4 = data['interfaces'][0]['ipv4']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-04
          • 2021-01-16
          • 2017-12-02
          • 2017-02-08
          • 2021-12-18
          • 1970-01-01
          • 2013-04-11
          • 2020-08-11
          相关资源
          最近更新 更多