Ross Thomas
Ross Thomas

Reputation: 31

Robot Framework - Convert JSON to dictionary

I am having a problem converting a JSON file to a dictionary with Robot Framework.

*** Variables ***
${MY_DATA_TABLE VALUES}
${MY_JSON_FILE}    *path_to_JSON\test.json*


*** Keywords ***
Converting a JSON File
    ${MY_DATA_TABLE_VALUES_TEMP}   get file   ${MY_JSON_FILE}
    ${MY_DATA_TABLE_VALUES}    evaluate  json.loads('''${MY_DATA_TABLE_VALUES_TEMP}''')    json
    ${MY_DATA_TABLE_VALUES}=       convert to dictionary   ${MY_DATA_TABLE_VALUES}
    [Return]  ${MY_DATA_TABLE_VALUES}

I am under the impression that the json.loads function will return a string and not a dictionary and that is why I am trying to convert to a dictionary.

I intend to access the variable ${MY_DATA_TABLE_VALUES} in a few more RF keywords.

Any guidance would be appreciated. Thanks

Upvotes: 3

Views: 23739

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

I am under the impression that the json.loads function will return a string and not a dictionary

That is incorrect. It returns a dictionary. You do not need to call convert to dict, your code works fine without it.

Here's a working example:

*** Settings ***
Library  Collections

*** Variables ***
${MY_DATA_TABLE_VALUES_TEMP}  {"foo": "this is foo", "bar": "this is bar"}

*** Keywords ***
Converting a JSON File
    ${MY_DATA_TABLE_VALUES}    evaluate  json.loads($MY_DATA_TABLE_VALUES_TEMP)    json
    [Return]  ${MY_DATA_TABLE_VALUES}

*** Test Cases ***
Example
    ${data}=  converting a json file
    ${datatype}=  evaluate  str(type($data))
    should be equal  ${datatype}  <class 'dict'>
    should be equal  ${data['foo']}  this is foo

    

Upvotes: 6

Related Questions