简体   繁体   English

如何使用机器人框架遍历JSON数组

[英]How to iterate over JSON array using robot framework

I want to iterate over json response and get the id and name elements data .My response json and code that i am trying is below. 我想遍历json响应并获取id和name元素数据。我正在尝试的响应json和代码如下。 Can someone let me know what mistake i am doing . 有人可以让我知道我在做什么错。

[
  {
    "id": 3,
    "policyRevId": 3,
    "busId": "POL_0003",
    "revision": 1,
    "name": "CIS Microsoft Windows Server 2012 R2 v2.2.1"
    },
  {
    "id": 2,
    "policyRevId": 2,
    "busId": "POL_0002",
    "revision": 1,
    "name": "CIS SUSE Linux Enterprise Server 11 Benchmark v 2.0"

  },
  {
    "id": 1,
    "policyRevId": 1,
    "busId": "POL_0001",
    "revision": 1,
    "name": "Payment Card Industry (PCI) Data Security Standard version 3.1"
  }
]


*** Settings ***
Library           RequestsLibrary
Library           Collections
Library           strings


*** Test case ***

Get Policy With Auth
    @{auth}=  Create List  user  pass
    Create Session    httpbin    https://test123.com/  auth=@{auth}
    ${resp}=  Get Request  httpbin  uri=/policies/
    :FOR   ${i}   in  ${resp.json()}
    \   Log  ${i}
    \   ${get_policy_id}=    Get Variable Value    ${resp.json()[i]['id']}
    \   ${policy_name}=    Get Variable Value    ${resp.json()[i]['name']}
    \   Log    ${policy_id},${policy_name}

The data in ${resp.json()} is a list, so you should be able to directly iterate over the items in the list. ${resp.json()}是一个列表,因此您应该能够直接迭代列表中的项目。 Notice in the following example that @ is used in the :FOR statement, and that ${item} is a dictionary rather than an index: 请注意,在以下示例中,在:FOR语句中使用@ ,并且${item}是字典而不是索引:

:FOR   ${item}   in  @{resp.json()}
\   Log  ${item}
\   ${get_policy_id}=  Set variable    ${item['id']}
\   ${policy_name}=    Set variable    ${item['name']}
\   Log    ${policy_id},${policy_name}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM