首页 文章

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

提问于
浏览
2

我有这样的嵌入字典:

${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创建的?

谢谢 .

1 回答

  • 6

    正如millimoose建议的那样,JSONDecoder返回的python字典与robotframework自己的字典不同 . 我还没有找到将python dict转换为机器人dict的官方方法,所以我实现了自己的:

    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}
    

    如果您需要将机器人dict转换为python dict,可以使用Collections库中的Convert To Dictionary关键字(http://robotframework.org/robotframework/latest/libraries/Collections.html#Convert%20To%20Dictionary) .

相关问题