【问题标题】:Robotframework : how to get all keys of JSON as listRobotframework:如何获取 JSON 的所有键作为列表
【发布时间】:2018-12-18 11:32:18
【问题描述】:

有人可以解释一下如何在机器人框架中获取 JSON 的所有键作为列表吗?

示例:

{
   "api": "rest",
   "framework": "robot-framework"
}

我必须获取属性列表(api、框架)

【问题讨论】:

    标签: python-3.x api automation robotframework


    【解决方案1】:

    您需要将 JSON 字符串转换为字典,然后在字典上调用keys 方法。对于后者,您可以使用内置关键字call method,或使用extended variable syntax

    例子:

    *** Variables ***
    ${json_string} 
        ...   {
        ...       "api": "rest",
        ...       "framework": "robot-framework"
        ...   }
    
    *** Test cases ***
    Example
    
        # convert the JSON to a python object
        ${json}=    evaluate    json.loads($json_string)    json
    
        # get the keys using `call method`
        ${keys}=  call method  ${json}  keys
        should contain  ${keys}  api
        should contain  ${keys}  framework    
    
        # get the keys using extended variable syntax
        ${keys}=  set variable   ${json.keys()}
        should contain  ${keys}  api
        should contain  ${keys}  framework    
    

    【讨论】:

    • 非常感谢.. 我需要的是露营两个 json 的所有键。我有两个很长的 json,我需要将两个应该相等的 json 的键放在一起
    • @saf:这不是您最初问题的一部分。您问如何获取密钥,这里显示如何获取密钥。
    【解决方案2】:

    另外,我使用的 Collections 库中有一个 Get Dictionary Keys 关键字。它完全符合您的要求:

    ${json} =    Convert To Dictionary    ${json}
    ${list} =    Get Dictionary Keys    ${json}
    
    Log    ${list}    #This should now give you api and framework
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 2012-08-06
      • 1970-01-01
      相关资源
      最近更新 更多