2017-03-17 75 views
1

我想遍歷json響應並獲取id和name元素數據。我的反應json和代碼,我正在嘗試下面。有人可以讓我知道我在做什麼錯誤嗎?如何迭代使用機器人框架的JSON數組

[ 
    { 
    "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/ [email protected]{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} 
+0

你得到一個錯誤?這段代碼的輸出與你期望的不同嗎? –

+0

@BryanOakley,我想迭代字典並獲取id,name值。我得到輸出爲None。 resp.json()包含keyvalues對 – Madhu

+0

當你記錄'$ {i}'時,日誌中顯示的是什麼? –

回答

2

的數據${resp.json()}是一個列表,所以你應該能夠直接遍歷在列表中的項目。在下面的例子@注意的是在: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} 
+0

謝謝@Bryan。有效。 – Madhu

+0

@Madhu你甚至可以考慮upvote答案:) –