Search code examples
robotframeworkweb-api-testing

Fetching a variable inside a list in ROBOT Framework


Suppose the below is my response body

body={
  "message": {
    "Code": 26181,
    "rollnos": [
      {
        "ID": 1439173,
        "date_input": "2022-01-31 14:09:30.206748",
      }
    ],
    "start_date": "2022-01-31 00:00:00",
  }
}

I want to set the ID value in a variable. I have tried the below but it did not work out.

  ${json_response}=  set variable    ${xyz.json()}
  
  ${temp}=  Set Variable    ${json_response['message']}
  
  ${value_1}=  Set Variable    ${temp['rollnos']}
  
  ${register_id} =  Set Variable    ${value_1["ID"]

Where have I gone wrong in this?


Solution

  • If you have body already as a dictionary you can use only the last 4 lines from the test example. I have included also the transformation from string to dictionary in case you need it:

    *** Settings ***
    Library  Collections
    
    Resource          robot/resources/environment_resources.robot
    
    *** Variables ***
    ${body_temp}    {"message": {"Code": "26181", "rollnos": [{"ID": "1439173", "date_input": "2022-01-31 14:09:30.206748"}],"start_date": "2022-01-31 00:00:00"}}
    
    *** Keywords ***
    Converting a JSON File
        ${body}    evaluate  json.loads($body_temp)    json
        [Return]  ${body}
    
    *** Test Cases ***
    Example
        # Get body as dict
        ${body}=  converting a json file
    
        # Get the ID
        ${message} =    Get From Dictionary     ${body}    message
        ${rollnos} =    Get From Dictionary     ${message}    rollnos
    
        ${id} =   Get From Dictionary     ${rollnos}[0]    ID
    
        # Log the ID
        Log To Console    ID:${id}