Ton*_*ana 3 json robotframework
{
"data": [
{
"name": "John",
"mobile_phone": false,
"carrier": "none"
},
{
"name": "Jim",
"mobile_phone": true,
"carrier": "T-Mobile"
}
],
"result": 0
}
Run Code Online (Sandbox Code Playgroud)
嗨,是否可以在Robot Framework中解析此类JSON响应,而我将为每个值创建一种“子”列表?我想将John与Jim分开,例如仅获取有关Jim的承运人的信息(通过稍后的测试中的另一个get请求)。谢谢 !
说源文本(json)存储在变量中${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
Run Code Online (Sandbox Code Playgroud)
此注释代码示例显示了如何在robotframework中使用json / dictionary对象。
第1行上的Evaluate关键字运行任意的python代码(其第一个参数调用loads()json模块的方法);它的第二个参数是需要导入的任何其他库,例如json。
第四行Set Variable显示扩展变量语法 -在这种情况下,知道这source data是一个字典,并获取该键的值。在此行执行的最后,变量all data members是json的“数据”键中的列表。
第8行在同一列表上开始循环;该变量member将在每次迭代中保存每个列表成员的值。
第9行使用另一种(更传统的)方式来获取字典键的值-通过使用Collections库中的关键字Get From Dictionary。
第10行通过使用常规(name)和扩展语法(member['mobile_phone'])变量记录一条消息。
在第11行上,将创建一个字典条目,其中将name用作键,将布尔值member['mobile_phone']用作值(如果已经有一个同名键-它将被覆盖)。此关键字再次在Collections库中。