首页 > 解决方案 > 如何使用机器人框架从 json 响应中读取所需的键、值并以 json 格式存储?

问题描述

我正在尝试从 JSON 响应中读取所需的键和值并将其存储在 JSON 文件中。

我有一个示例简化的 json 格式,如下所示:

 ${API_Output}= {
"data": {
"resources": {
"edges": [
{
"node": {
    "tags": [],
   }
},
{          
  "node": {
   "tags": [
      {
        "name": "app",
        "value": "e2e"
      },
      {
        "name": "Cost",
         "value": "qwerty"
      }
  }
},
{          
  "node": {
   "tags": [
      {
        "name": "app",
        "value": "e2e"
      },
      {
        "name": "Cost",
         "value": "qwerty"
      },
        {
        "name": "test",
         "value": "qwerty"
      }
  }
}
]
}
}
}

在这里,我正在阅读存在的标签名称和值。我使用了字典键“设置为字典”,但它只打印标签的最后一个响应。

我想知道如何将数据附加或添加到字典中并以 JSON 格式存储。

我用过的机器人代码:

 ${dict1}=        Set Variable  ${API_Output}
 ${cnt}=     get length     ${dict1['data']['resources']['edges']}
 ${edge}=   set variable      ${dict1['data']['resources']['edges']}

 run keyword if   ${cnt}==0     set test message    The resources count is 
  Zero(0)
  log to console  ${cnt}-count

: FOR    ${item}    IN RANGE   0    ${cnt}
 \    ${readName}=    Set Variable     ${edge[${item}]['node'] 
       ['configuration']}
 \    ${readvalue2}=    Set Variable     ${edge[${item}]['node']['tags']}
  \    ${tag_Count}=    get length     ${edge[${item}]['node']['tags']}
 \    ${tag_variable}=   set variable   ${edge[${item}]['node']['tags']}
 \    forkeyword       ${tag_Count}   ${tag_variable}    ${readName}

 ${req_json}    Json.Dumps    ${dict}
 Create File  results.json  ${req_json}


forkeyword
[Arguments]       ${tag_Count}      ${tag_variable}     ${readName}
@{z}=   create list
 : FOR    ${item}    IN RANGE   0    ${tag_Count}
     \   ${resourceName}=    run keyword if     ${tag_Count} > 0   set 
     variable    ${readName['name']}
     \   log to console  ${resourceName}-forloop
     \   ${readkey}=     set variable   ${tag_variable[${item}]['name']}
     \   ${readvalue}=     set variable   ${tag_variable[${item}]['value']}
     \   set to dictionary     ${dict}     resourceName   ${resourceName}
     \   set to dictionary  ${dict}    ${readkey}     ${readvalue}
 set suite variable ${dict}

输出在 Values.json 文件中,我只得到最后一个标签值。

        {
        "name": "app",
        "value": "e2e"
      },
      {
        "name": "Cost",
         "value": "qwerty"
      },
        {
        "name": "test",
         "value": "qwerty"
      }

但是,我需要两个标签的所有标签值。谁能指导我如何使用字典或列出关键字?将所有标签的响应存储在文件中。我是机器人框架的新手,所以如果我犯了任何错误,我深表歉意。

标签: jsonpython-3.xlistdictionaryrobotframework

解决方案


推荐阅读