3
votes

I have embedded dictionaries like this:

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

I can access original key-value pairs like for example this:

${return.request.body.type}

It all works fine. However, I get this error:

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

When I try to create the initial json object vice-versa - by decoding it from string like this:

${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}

and accessing it via dot notation:

${detail_call.response.json.type}

When I log the string, I can clearly see there is key "type" with a value assigned. It even works when I access it with brackets:

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

Do you have any idea, why I can't use dot notation if the dictionary was created with JSONDecoder?

Thanks.

1
I'm confused by this question. You don't access dictionaries (that is, dicts specifically) using dot notation in Python in the first place, unless you're using a different dictionary implementation that allows that. Dot notation is used for attributes of objects, but JSONDecoder returns dicts, so it's perfectly normal to use brackets to access their keys. Also your sample code doesn't seem to be valid Python, is that syntax specific to the Robot framework? - millimoose
I think you've nailed it, I guess it is indeed different dict implementation. I'm not very familiar with python, only with robot and in it's syntax it is possible to access dicts with dots. - Samuel
It's entirely possible Robot just creates plain objects, not dictionaries, since it's not really much harder to set attributes in Python dynamically. - millimoose
It is, thank you for helping me out :) - Samuel

1 Answers

9
votes

As millimoose suggested, JSONDecoder returns python dictionary which is different from robotframework's own dictionary. I haven't found official way to convert python dict to robot dict so I have implemented my own:

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}

In case you need to convert robot dict to python dict, you can use Convert To Dictionary keyword from Collections library.