我有一个带有嵌套值的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"
}
}
}
]
}
}
}
机器人框架代码:
${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}
我希望所有标签都包含所有值,但只有最后一个标签键和值会被打印出来。谁能指导我输入代码。
在此先感谢您的帮助!
答案 0 :(得分:1)
为什么您首先有重复的键?
规范未涵盖JSON中的重复键,并且可能导致未定义的行为。如果将JSON读入Python字典,则信息将丢失,因为Python字典键必须唯一。最好的选择是更改JSON。重复键是个坏主意
此外,如果将json更改为没有重复项,则会给出正确的结果 因为python键必须是唯一的。
由于所有其他键都是重复的,因此简化版本为:
"data": {
"resources": {
"edges": [
{
"node": {
"tags": [
{
"name": "app",
"value": "e2e"
},
{
"name": "Cost",
"value": "qwert"
},
{
"name": "test",
"value": "qwerty"
}
]
}
}
]
}
}
因此,如果您的机器人框架给出的结果为
{
"name": "app",
"value": "e2e"
},
{
"name": "Cost",
"value": "qwert"
},
{
"name": "test",
"value": "qwerty"
}
是正确的。