在Robot Framework中解析Json

时间:2018-08-28 08:38:52

标签: json robotframework

document.getElementById('myInfiniteScroll').addEventListener('scroll', this.infiniteScroll);

嗨,是否可以在Robot Framework中解析此类JSON响应,而我将为每个值创建一种“子”列表? 我想将John与Jim分开,例如仅获取有关Jim的承运人的信息(通过稍后的测试中的另一个get请求)。 谢谢 !

1 个答案:

答案 0 :(得分:4)

说源文本(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

此注释代码示例显示了如何在robotframework中使用json / dictionary对象。

第1行的Evaluate keyword运行任意python代码(它的第一个参数调用json模块的loads()方法);它的第二个参数是需要导入的任何其他库,例如json。

第四行Set Variable显示Extended variable syntax-在这种情况下,知道source data是一个字典,得到该键的值。在此行执行的最后,变量all data members是json的“数据”键中的列表。

第8行在同一列表中以a loop开始;变量member将在每次迭代中保存每个列表的成员的值。

第9行使用另一种(更传统的)方法来获取字典键的值-通过使用“收藏”库中的关键字Get From Dictionary

第10行使用普通(name)和扩展语法(member['mobile_phone'])变量记录一条消息。

在第11行,将创建一个字典条目,其中将name用作键,并将布尔值member['mobile_phone']用作值(如果已经有一个同名键-它被覆盖)。此关键字再次位于Collections library中。