Access Dictionary element inside the list in RobotFramework display error list object has no attribute

孤街醉人 提交于 2019-12-10 22:35:22

问题


Here is program code, I have one json file code.json which structure is like this : [ {key:value}, {key:value} ]

When I convert list element into dictionary , it throws error

*** Settings ***
Library  JSONLibrary
Library  OperatingSystem
Library  unicodelist.py
Library  Collections

*** Test Cases ***
test json data1

    ${json_obj}=    Get file  code.json
    ${getfile}=  evaluate    json.loads('''${json_obj}''')    json
    #getfile contain json of list with dictionary
    ${obj}=  Convert To List  ${getfile}
    log to console   ${obj}
    #converted sucessfully
    log to console  " Display 1"
    #just log
    ${length}=  get length  ${obj}
    log to console  ${length}
    ${list0} =  Get From List  ${obj}  0
    log to console  ${list0}
    #list0 contain first dictionary element inside the list
    ${convert}=  Convert To Dictionary  ${list0}
    log to console  ${convert}
    # no error
    log to console  " Display 2"
    ${get_item} =  Get Dictionary Keys  ${obj}
    log to console   ${get_item}
    #error list' object has no attribute 'Keys'
    log to console  " Display 3"
    ${get_item} =  Copy Dictionary   ${obj}
    log to console   ${get_item}
    # error list' object has no attribute 'copy'

回答1:


You seem to be doing a whole lot of needless converting of data, and you're confusing the types of the objects.

Your code works if you remove all of the unnecessary conversions. It also helps if you use more descriptive variable names.

Example:

*** Settings ***
Library  OperatingSystem
Library  Collections

*** Test Cases ***
test json data1

    # ${json_data} is a string of characters
    ${json_data}=    Get file  code.json

    # ${obj_list} is a list of dictionaries
    ${obj_list}=  evaluate    json.loads('''${json_data}''')    json
    log to console  \nobj_list: ${obj_list}

    # ${obj} is the first dictionary in the list
    ${obj} =  Get From List  ${obj_list}  0
    log to console  obj: ${obj}

    # ${keys} is a list of keys
    ${keys} =  Get Dictionary Keys  ${obj}
    log to console   keys: ${keys}

    # ${new_obj} is a copy of the original obj
    ${new_obj} =  Copy Dictionary   ${obj}
    log to console   new_obj: ${new_obj}


来源:https://stackoverflow.com/questions/47522453/access-dictionary-element-inside-the-list-in-robotframework-display-error-list-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!