NeelamS
NeelamS

Reputation: 89

How can I extract one value using another value in json in robot framework

As part of verification in Robot Framework, I have following data (stored as ${resp}) as get request response:

{
   "numberOfElements": 2,
   "data": [
      {
         "id": "1",
         "accId": "123456789",
         "total": 13,
         "isEnabled": false
      },
      {
         "id": "2",
         "accId": "987654321",
         "total": 52,
         "isEnabled": false
      }
   ],
   "last": true
}

From the above json, I want to extract id whose accId is 123456789. How can I use condition parameters to search for a value using any other value from the json. I have implemented this code for verifying numberFfElemets

${json_resp} =    Set Variable    ${resp.json()}
${numberOfElements}  set variable  ${json_resp['numberOfElements']}
should be equal as numbers  ${numberOfElements}  2

Upvotes: 1

Views: 3025

Answers (3)

Alexey
Alexey

Reputation: 121

Corrected code

'Exit for loop' help to not rewrite ${id} to none

    *** Test Cases *** 
   Test1
        :FOR  ${i}  IN  @{json_resp()['data']}
        \   ${id}=  run keyword if  '${i['accId']}'=='123456789'     Get Id   ${i}
        \   run keyword if   '${i['accId']}'=='123456789'    Exit For Loop
            log to console  ${id}
    
    *** Keywords ***
    Get Id
        [Arguments]  ${content_body}
        ${idf}=  Get From Dictionary  ${content_body}  id
        [Return]  ${idf}

Upvotes: 0

NeelamS
NeelamS

Reputation: 89

Got the following solution to this problem and it works for me :

${uuid}=  set variable
:FOR  ${i}  IN  @{json_resp['data']}
\   ${uuid}=  run keyword if  '${i['id']}'=='123456789'     get uuid with id   ${i}
    log to console  ${uuid}
Get UUID With Id
    [Arguments]  ${content_body}
    ${uuid}=  Get From Dictionary  ${content_body}  uuid
    [Return]  ${uuid}

Upvotes: 1

Sidara KEO
Sidara KEO

Reputation: 1709

The simple step try to convert your json to dictionary and loop thought dictionary.

 ${json_resp} =    Set Variable    ${resp.json()}
 ${json}=    evaluate    json.loads('''${json_resp}''')    json
  :FOR  ${i}  IN  @{json['data']}
  \   log to Console      ${i['accId']}

Then you should can access to accId.

Upvotes: 0

Related Questions