如何在机器人框架上从 .json 获取父键
how to get parent key from .json on robot framework
我正在使用 Robot Framework 来做一些自动化工作。
想想我有一个这样的 JSON 文件。
{
"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,
}
}
}
我想获取两种类型的参数。首先是“Ethernet1/1”和“Ethernet1/2”;其次是属于“in_crc_errors”的“0”和“10”。
现在我可以使用 YamlPath Parse data=${JSON} query=**.in_crc_errors
来获取“in_crc_errors”
这样的输出{0, 10}
我的问题是如何获得父键“Ethernet1/1”和“Ethernet1/2”?
这样的预期输出{Ethernet1/1:0, Ethernet1/2:10}
您可以将 json 转换为字典并提取您需要的值并将它们设置为新字典。
示例代码如下:
*** 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}
我正在使用 Robot Framework 来做一些自动化工作。 想想我有一个这样的 JSON 文件。
{
"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,
}
}
}
我想获取两种类型的参数。首先是“Ethernet1/1”和“Ethernet1/2”;其次是属于“in_crc_errors”的“0”和“10”。
现在我可以使用 YamlPath Parse data=${JSON} query=**.in_crc_errors
来获取“in_crc_errors”
这样的输出{0, 10}
我的问题是如何获得父键“Ethernet1/1”和“Ethernet1/2”?
这样的预期输出{Ethernet1/1:0, Ethernet1/2:10}
您可以将 json 转换为字典并提取您需要的值并将它们设置为新字典。
示例代码如下:
*** 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}