简体   繁体   中英

how to get parent key from .json on robot framework

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 "Ethe.net1/1" and "Ethe.net1/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 "Ethe.net1/1" and "Ethe.net1/2" as well?

Expected output like this {Ethe.net1/1:0, Ethe.net1/2:10}

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM