如何从json响应中读取所需的键和值,并使用机器人框架将其存储为json格式?

时间:2019-11-11 07:46:48

标签: json python-3.x list dictionary robotframework

我正在尝试从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"
      }

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

0 个答案:

没有答案