原文鏈接
本文節選自霍格沃茲測驗開發學社內部教材
在之前的的章節已經簡單介紹了如何斷言介面的回應值,在實際作業程序中,json 的回應內容往往十分復雜,面對復雜的 json 回應體,主要通過 JSONPath 解決,JSONPath 提供了強大的 JSON 決議功能,使用它自帶的類似 XPath 的語法,可以更便捷靈活的用來獲取對應的 JSON 內容,
環境準備
Python 版本安裝
pip install jsonpath
Java 版本安裝
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.6.0</version>
</dependency>
XPath 和 JSONPath 語法
下表是 XPath 和 JSONPath 語法進行對比,這兩者的定位方式,有著非常多的相似之處:
比如同樣一個欄位,XPath 中的語法是:
/store/book[0]/title
JSONPath 的語法是:
$.store.book[0].title
$['store']['book'][0]['title']
下面是一組 json 結構,分別通過 JSONPath 和 XPath 的方式提取出來
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
下表列出了 XPath 與 JSONPath 的對比:

更多內容請訪問:https://goessner.net/articles/JsonPath
實戰練習
以下是 https://ceshiren.com/t/topic/6950.json 這個介面的正常回應值(因回應篇幅過長,洗掉了部分內容):
{
'post_stream': {
'posts': [
{
'id': 17126,
'name': '思寒',
'username': 'seveniruby',
'avatar_template': '/user_avatar/ceshiren.com/seveniruby/{size}/2_2.png',
'created_at': '2020-10-02T04:23:30.586Z',
'cooked': '<p>一直以來的平均漲薪率在30%以上,這次重繪的記錄估計要保持好幾年了</p>',
'post_number': 6,
'post_type': 1,
'updated_at': '2020-10-02T04:23:48.775Z',
'reply_to_post_number': None,
'reads': 651,
'readers_count': 650,
'score': 166.6,
'yours': False,
'topic_id': 6950,
'topic_slug': 'topic',
'display_username': '思寒',
'primary_group_name': 'python_12',
...省略...
},
],
},
'timeline_lookup': ,
'suggested_topics':,
'tags': [
'精華帖',
'測驗開發',
'測驗求職',
'外包測驗'
],
'id': 6950,
'title': '測驗人生 | 從外包菜鳥到測驗開發,薪資一年翻三倍,連自己都不敢信!(附面試真題與答案)',
'fancy_title': '測驗人生 | 從外包菜鳥到測驗開發,薪資一年翻三倍,連自己都不敢信!(附面試真題與答案)',
}
接下來則需要實作一個請求,斷言以上的回應內容中 name 欄位為'思寒'所對應的 cooked 包含"漲薪"
Python 演示代碼
JSONPath 斷言
import requests
from jsonpath import jsonpath
r = requests.get("https://ceshiren.com/t/topic/6950.json").json()
result = jsonpath(r, "$..posts[?(@.name == '思寒')].cooked")[1]
assert "漲薪" in result
Java 演示代碼
JSONPath 斷言
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
public class jsonTest {
@Test
void jsonTest() {
//獲取回應資訊,并轉成字串型別
String res = given().when().
get("https://ceshiren.com/t/topic/6950.json")
.then().extract().response().asString();
//通過jsonpath運算式提取需要的欄位
List<String> result = JsonPath.read(res, "$..posts[?(@.name == '思寒')].cooked");
// 斷言驗證
assert result.get(1).contains("漲薪");
}
}
喜歡軟體測驗的小伙伴們,如果我的博客對你有幫助、如果你喜歡我的博客內容,請 “點贊” “評論” “收藏” 一鍵三連哦,更多技術文章
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/500790.html
標籤:其他
上一篇:【真送禮物】1 分鐘 Serverless 極速部署盲盒平臺,自己部署自己抽!
下一篇:docker的相關命令
