无法在Robot Framework中使用点表示法访问字典

3 投票
2 回答
4737 浏览
提问于 2025-05-10 15:00

我有嵌套字典,像这样:

${json}=    Create Dictionary ......(value pairs)
${request}= Create Dictionary   body=${json}
${return}=  Create Dictionary   request=${request}

我可以像这样访问原始的键值对:

${return.request.body.type}

一切都运行得很好。不过,我遇到了这个错误:

Resolving variable '${detail_call.response.json.type}' failed: AttributeError: 'dict' object has no attribute 'type'

当我尝试反向创建初始的json对象,也就是从字符串解码时,像这样:

${decoded_json}=    Run Keyword And Ignore Error    json.JSONDecoder.Decode ${response.content}
${response.json}=   Set Variable If '${decode_status}' == 'PASS'    ${decoded_json} ${null}
${detail_call}=    Create Dictionary    response=${response}

然后通过点符号来访问它:

${detail_call.response.json.type}

当我打印这个字符串时,我可以清楚地看到有一个键叫“type”,并且有一个值被赋给它。用括号访问时也能正常工作:

${detail_call.response.json['type']}

你知道为什么如果字典是用JSONDecoder创建的,我就不能使用点符号吗?

谢谢。

相关文章:

  • 暂无相关问题
暂无标签

2 个回答

0

Robot Framework 有一个自己的字典类叫做 DotDict,这个类可以让你用点号来访问(嵌套的)字典。使用 Robot Framework 的 DSL(领域特定语言),你可以通过三种方式来创建一个 DotDict:

  1. 使用关键字 Create Dictionary(就像你已经发现的那样)
  2. 在设置部分 创建一个字典变量
  3. 将一个字典变量(例如 &{robot_dict})作为关键字的返回值来赋值

第三种方式就是你想要的。

10

正如millimoose所提到的,JSONDecoder会返回一个Python字典,这和Robot Framework自己的字典是不同的。我还没有找到官方的方法来把Python字典转换成Robot字典,所以我自己实现了一个:

Convert Python Dictionary
[Arguments]    ${python_dict}
[Documentation]    Converts Python dictionary to Robot dictionary.
@{keys}=    Get Dictionary Keys    ${python_dict}
${robot_dict}=    Create Dictionary
:FOR    ${key}    IN    @{keys}
\    Set To Dictionary    ${robot_dict}    ${key}=${python_dict['${key}']}
[Return]    ${robot_dict}

如果你需要把Robot字典转换成Python字典,可以使用Collections库中的Convert To Dictionary这个关键字。

撰写回答