Auto-learner
Auto-learner

Reputation: 1511

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. 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}

Upvotes: 2

Views: 13175

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

The data in ${resp.json()} is a list, so you should be able to directly iterate over the items in the list. Notice in the following example that @ is used in the :FOR statement, and that ${item} is a dictionary rather than an index:

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

Upvotes: 9

Related Questions