问题
{
"data": [
{
"name": "John",
"mobile_phone": false,
"carrier": "none"
},
{
"name": "Jim",
"mobile_phone": true,
"carrier": "T-Mobile"
}
],
"result": 0
}
Hi, will it be possible to parse such JSON response in Robot Framework in a way where I will create kind of 'sub' list for each value ? I would like to separate John from Jim and get for example information about carrier for Jim only (via another get request later in test). Thanks !
回答1:
Say the source text (the json) is stored in a variable ${source data}
:
${source data}= Evaluate json.loads("""${source data}""") json
# the variable ${source data} is now a python dictionary - the same as the original json, but only - accessible as dictionary in robotframwork
${all data members}= Set Variable ${source data['data']}
${user_phone}= Create Dictionary
:FOR ${member} IN @{all data members} # iterate through the 'data', each ${member} is a dictionary in the source list
\ ${name}= Get From Dictionary ${member} name # will assign to the variable ${name} the value of the key 'name'; if there is no such key - the keyword will fail
\ Log The user ${name} has a mobile phone: ${member['mobile_phone']} # Will print "The user John has a mobile phone: False", "The user Jim has a mobile phone: True"
\ Set To Dictionary ${user_phone} ${name} ${member['mobile_phone']} # will fill-in a dictionary in the form "name": boolean_does_the_person_has_phone
This commented code sample shows how you can work with json/dictionary objects in robotframework.
The Evaluate keyword on line 1 runs arbitrary python code (its first argument, which calls the loads()
method of the json module); its 2nd argument is any extra libraries that need to be imported - like json in our case.
The 4th line, Set Variable
shows the Extended variable syntax - in this case, knowing that source data
is a dictionary, getting the value of that key. At the end of this line execution, the variable all data members
is the list that's inside the json's 'data' key.
Line 8 starts a loop, over that same list; the variable member
will hold the value of each list's member on every iteration.
Line 9 uses a different (more orthodox) way to get the value of a dictionary's key - by using the keyword Get From Dictionary from the Collections library.
Line 10 logs a message, by employing a normal (name
) and extended syntax (member['mobile_phone']
) variables.
And on line 11, a dictionary entry is created, where the name
is used as a key, and the boolean member['mobile_phone']
as a value (if there is already a key with the same name - it is overwritten). This keyword is again in the Collections library.
来源:https://stackoverflow.com/questions/52053569/parsing-json-in-robot-framework