在Python / RobotFramework中,我应该如何将所需的键,值从嵌套json附加到另一个文件中?

问题描述 投票:0回答:2

我有以下格式的嵌套JSON,我需要从中获取标签的名称和值,如果重复出现在另一个json文件中,则将其追加。

${resp}= {
"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文件中。参见下面我尝试过的Python代码。

Python代码:

def appendjsondata(fileName,data):
 new = {}
 print (data)
 print('forloop before')
 for k,v in data.items():

    print(f'{k}: {v}')
    new["key"] = k
    new["tags"] = []
    new["value"] = v

    #new["tags"].append([{ 'key': k, 'values': v } for k, v in data.items()])
    new["tags"].append(new)
 print(new["tags"])
 with open(fileName, 'w') as f:
   json.dump(new["tags"], f, indent=3 * ' ')  

 return  new["tags"]

机器人框架代码:

*** Settings ***
Library pythonfile.py
Library   JSONLibrary
Library   Collections

*** Test Cases ***
${dict1}=        Set Variable  ${resp}
${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']}
\    ${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}
         \    appendjsondata      results.json    ${dict}
set suite variable ${dict}

错误:

未找到关键字appendjsondata

python json list append robotframework
2个回答
1
投票

机器人文件无法识别python程序中定义的关键字。检查以下步骤:

1。检查python程序没有编译问题,并且已正确导入。控制台将显示错误消息。

  1. 在您的python类定义中添加ROBOT_LIBRARY_SCOPE ='TEST SUITE'。

0
投票

“库”导入中只有一个空格。在导入中使用两个或多个空格,例如Library pythonfile.py

并检查pythonfile.py与RF文件位于同一目录中。

© www.soinside.com 2019 - 2024. All rights reserved.