uhimh
uhimh

Reputation: 31

Robotframework : how to get all keys of JSON as list

Can someone explain me how to get all keys of JSON as list in robot framework?

example:

{
   "api": "rest",
   "framework": "robot-framework"
}

I have to get list of properties (api,framework)

Upvotes: 1

Views: 4742

Answers (2)

Lubos Jerabek
Lubos Jerabek

Reputation: 833

Alternatively, there is a Get Dictionary Keys keyword in the Collections library that I use. It does exactly what you're after:

${json} =    Convert To Dictionary    ${json}
${list} =    Get Dictionary Keys    ${json}

Log    ${list}    #This should now give you api and framework

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386010

You need to convert the JSON string to a dictionary, and then call the keys method on the dictionary. For the latter you can use the built-in keyword call method, or use extended variable syntax.

Example:

*** Variables ***
${json_string} 
    ...   {
    ...       "api": "rest",
    ...       "framework": "robot-framework"
    ...   }

*** Test cases ***
Example

    # convert the JSON to a python object
    ${json}=    evaluate    json.loads($json_string)    json

    # get the keys using `call method`
    ${keys}=  call method  ${json}  keys
    should contain  ${keys}  api
    should contain  ${keys}  framework    

    # get the keys using extended variable syntax
    ${keys}=  set variable   ${json.keys()}
    should contain  ${keys}  api
    should contain  ${keys}  framework    

Upvotes: 1

Related Questions