【发布时间】:2022-11-24 00:47:57
【问题描述】:
所以我遇到了这个问题,我需要检查我的 JSON 文件中是否存在密钥,并基于此继续我的操作。所以我在做
Add Item To JSON
[Documentation] This keyword is designed to add an Item to JSON file
[Arguments] ${json_file} ${item_ref}
${item_details} Create Dictionary something=${some_string}
#Adding all my details here
${item_list} Create List ${item_details}
#Check if there are any items already added to Add item To JSON
${is_item_key_exist} Run Keyword And Return Status Dictionary Should Contain Key ${json_file} Items
# If Items key does not exists, then add the item to JSON
IF ${is_item_key_exist}
${json_file}= Add Object To Json ${json_file} $..Items ${item_details}
#Otherwise create Items key and add details into it
ELSE
${items} Create Dictionary Items=${item_list}
${json_file}= Add Object To Json ${json_file} $.value.containers[0] ${items}
END
[Return] ${json_file}
这就是我的 json 的样子
"containers": [
{ "Items": [
{
"emptyFullIndicatorCode": "1/1",
"emptyWeight": "0",
"goods": "goods",
"goodsWeight": "1",
"numberOfPackages": "1",
"packagingTypeCode": "PK",
"packagingTypeName": "Colis (\"package\")",
"reference": "YYYY1234567",
"typeCode": "18R0"
}
]
}
因此,在这种情况下,当 JSON 中存在实际的密钥项时,我的代码会在检查密钥是否确实存在时返回 false。 我认为这是因为关键项目位于另一个关键容器内的数组内,但我找不到如何精确定位它的解决方案。
尝试通过 Collections.py 库中的不同关键字访问它,但我从来没有做对。 如果我尝试通过检查 Containers 键来执行相同的场景 - 它工作正常。
【问题讨论】:
-
您能否在您的示例 JSON 中突出显示您想要查找的内容以及您的预期输出是什么?即给定 Func("PK") = True?或 Func("package") = TRUE?另外,您是否有固定的深度,或者您正在寻找更糟糕的完全递归算法?
-
我想做的是找出为什么 ${is_item_key_exist} Run Keyword And Return Status Dictionary Should Contain Key ${json_file} Items IF ${is_item_key_exist} line is not working, and it always throws False, where obviously the Items key Json里面有吗
-
是否有必要保持 JSON 的格式?也就是说,您可以将其重新格式化为没有数组/列表的正确格式,然后您的机器人框架代码应该没问题。否则,有条件地检查键的结果是否为数组,并对每个数组的键进行另一次检查。
-
@JasonChia 是的,我有必要保持它的格式,因为它应该稍后作为请求正文传递 - 所以当我尝试更改它时,请求根本不起作用
标签: python arrays json collections robotframework