【问题标题】:How to check if key exists inside JSON file, if the key is inside an Array in JSON (ROBOT FRAMEWORK)如何检查 JSON 文件中是否存在键,如果键在 JSON 中的数组中(ROBOT FRAMEWORK)
【发布时间】: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


【解决方案1】:

@The Leviathan,我不太熟悉 robotframework 但考虑以下 python 递归:

def check_keys(search_key,data):
    return_value = False
    for key,value in data.items():
        if search_key == key:
            return_value = True
        else:    
            dict_test = check_list(search_key,value) #<-recursion
            if dict_test:
                  return_value = True
            else:
                 pass
    return return_value
                    

def check_list(search_key,x): #Checks that the 'value' is not a list containing a dict.
    return_value = False
    if isinstance(x,list):
        for item in x:
            if isinstance(item,dict):
                return_value = check_keys(search_key,item)
    return return_value

如果里面还有另一层字典,基本上会检查每个值。

x = {"containers": [
  {    "Items": [
      {
        "emptyFullIndicatorCode": "1/1",
        "emptyWeight": "0",
        "goods": "goods",
        "goodsWeight": "1",
        "numberOfPackages": "1",
        "packagingTypeCode": "PK",
        "packagingTypeName": "Colis ("package")",
        "reference": "YYYY1234567",
        "typeCode": "18R0"
      }
    ]
  }]}

check_keys('containers',x) -> True
check_keys('Items',x)->True
check_keys('goodsWeight',x)->True
check_keys('magic',x) -> False

不确定如何在 robotframework 中实现,但这是一个不修改 JSON 的递归解决方案,而且可能也不是最优的。

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2021-06-27
    • 2022-07-12
    • 1970-01-01
    相关资源
    最近更新 更多