Home > other >  how to get parent key from .json on robot framework
how to get parent key from .json on robot framework

Time:04-07

I'm using Robot Framework to do some automation work. Think about that I have a JSON file like that.

{
"Ethernet1/1": {
    "port_channel": {
      "port_channel_member": false
    },
    "counters": {
      "rate": {
        "load_interval": 300,
      },
      "rx": true,
      "in_crc_errors": 0,
    }
  },
"Ethernet1/2": {
    "port_channel": {
      "port_channel_member": false
    },
    "counters": {
      "rate": {
        "load_interval": 300,
      },
      "rx": true,
      "in_crc_errors": 10,
    }
  }
}

I want to get two types of parameter. First is "Ethernet1/1" and "Ethernet1/2" ; Second is "0" and "10" which belongs to "in_crc_errors".

Now I can use YamlPath Parse data=${JSON} query=**.in_crc_errors to get "in_crc_errors"

Output like that {0, 10}

My question is how can I get the parent key "Ethernet1/1" and "Ethernet1/2" as well ?

Expected output like this {Ethernet1/1:0, Ethernet1/2:10}

CodePudding user response:

It's possible you can convert the json to a dictionary and extract the values you need and set them to a new dictionary.

Example code below:

*** Settings ***
Library   OperatingSystem
Library   Collections


*** Test Cases ***
Extract From Json
    
    # Get Json from File
    ${json}  Get File  test.json

    # Convert json to dictionary
    ${data}  Evaluate  json.loads('''${json}''')

    # Init an empty dictionary for extracted values
    &{extracted_values_dict}  Create Dictionary

    FOR  ${eth}  IN  @{data}

        # Next we need the data within so we use the ${eth} value as key and lookup the other values within ${data}
        ${crc_errs}  Set Variable  ${data}[${eth}][counters][in_crc_errors]

        # We can add key "${eth}" and value "${crc_errs}" to the extracted values dict
        Set To Dictionary   ${extracted_values_dict}  ${eth}=${crc_errs}

    END

    log to console  ${extracted_values_dict}
  • Related