【问题标题】:Parsing Json in Robot Framework在 Robot Framework 中解析 Json
【发布时间】:2019-02-02 20:00:10
【问题描述】:
{
  "data": [
    {
      "name": "John",
      "mobile_phone": false,
      "carrier": "none"
    },
    {
      "name": "Jim",
      "mobile_phone": true,
      "carrier": "T-Mobile"
    }
  ],
  "result": 0
}

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

【问题讨论】:

  • 显示您尝试过的代码,以及您遇到的问题。所有用于 http 请求的 RF 库 - 正如您的问题所暗示的那样 - 都有某种 json -> 字典转换。而且如果你不使用这样的库,在 python 中解析 json 是微不足道的。
  • 您好,感谢您的评论。我不知道如何处理关键“数据”的值列表。我也不知道如何搜索 John 对于键“mobile_phone”的值为 false 或 true,因为有更多具有相同“名称”的键。因此我想我必须先创建多个列表,然后再搜索。

标签: json robotframework


【解决方案1】:

假设源文本(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/字典对象。

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

第 4 行 Set Variable 显示 Extended variable syntax - 在这种情况下,知道 source data 是一个字典,获取该键的值。在这一行执行结束时,变量 all data members 是 json 的“数据”键内的列表。

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

第 9 行使用不同的(更正统的)方法来获取字典键的值 - 使用 Collections 库中的关键字 Get From Dictionary

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

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

【讨论】:

  • 嗨,这是一个很好的评论,解释了很多。但无论如何,第 9 行每次都会失败,因为字典是空的。我会说它应该首先创建,或者?
  • 那些字典已经创建 - 它们是“数据”值中的列表成员。
猜你喜欢
  • 2017-01-20
  • 2014-03-29
  • 1970-01-01
  • 2017-06-18
  • 2018-04-27
  • 2019-04-22
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
相关资源
最近更新 更多