您能否建议如何在Robot Framework中使用JsonPath? 它应该支持多级查询,如下所示:
CSS
我正在寻找下列工作的方法:
$.items[?(@.status.name="closed")].name
像这样
答案 0 :(得分:1)
此RF代码可满足您的需求,但仅适用于提供的json结构。从我的角度来看,你应该玩Get Json Value
并准备你需要的关键词。顺便说一下,很明显RF中的这种json /字符串处理有点复杂,所以我宁愿用你需要的关键字编写小的Python库。
*** Settings ***
Library Collections
Library HttpLibrary.HTTP
*** Variables ***
${json} {"items":[{"name":"item1","status":{"id":1,"name":"opened"}},{"name":"item2","status":{"id":2,"name":"closed"}}]}
${name} ${EMPTY}
${result} ${EMPTY}
*** Test Cases ***
Get Closed Item
${name} Get Name By Status ${json} closed
Should Be Equal As Strings ${name} item2
${name} Get Name By Status ${json} opened
Should Be Equal As Strings ${name} item1
*** Keywords ***
Get Name By Status
[Arguments] ${json} ${status}
[Return] ${result}
${json} Parse Json ${json}
:FOR ${item} IN @{json["items"]}
\ ${item} Stringify Json ${item}
\ ${name} Get Json Value ${item} /name
\ ${name} Parse Json ${name}
\ ${status_name} Get Json Value ${item} /status/name
\ ${status_name} Parse Json ${status_name}
\ ${result} Set Variable If '${status_name}' == '${status}' ${name} ${result}
编辑:根据下面的评论,我会选择基于python的代码。
JsonpathLibrary.py
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import jsonpath
class JsonpathLibrary(object):
def get_items_by_path(self, json_string, json_path):
json_object = json.loads(json_string)
match_object = jsonpath.jsonpath(json_object, json_path)
match_string = json.dumps(match_object[0])
return match_string
RF代码:
*** Settings ***
Library JsonpathLibrary.py
*** Variables ***
${json} {"items":[{"name":"item1","status":{"id":1,"name":"opened"}},{"name":"item2","status":{"id":2,"name":"closed"}}]}
${json_path} $.items[?(@.status.name=="closed")].name
*** Test Cases ***
Some Descriptive Name Here
${name} Get Items By Path ${json} ${json_path}
Should Be Equal As Strings ${name} "item2"