{
"data": [
{
"name": "John",
"mobile_phone": false,
"carrier": "none"
},
{
"name": "Jim",
"mobile_phone": true,
"carrier": "T-Mobile"
}
],
"result": 0
}
嗨,是否可以在 Robot Framework 中以我将为每个值创建一种“子”列表的方式解析此类 JSON 响应?
我想将 John 与 Jim 分开,并仅获取有关 Jim 的运营商的信息(通过稍后在测试中的另一个获取请求)。
谢谢 !
最佳答案
假设源文本(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
这个带注释的代码示例展示了如何在机器人框架中使用 json/dictionary 对象。
Evaluate keyword第 1 行运行任意 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
用作键, bool 值 member['mobile_phone']
作为一个值(如果已经有一个同名的键 - 它被覆盖)。此关键字再次出现在 Collections library 中.
关于json - 在 Robot Framework 中解析 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52053569/