JSONPath 是一種查詢語言,設計用於從 JSON 資料結構中擷取資訊,類似於 XPath 對 XML 的作用。在 Apidog 中,JSONPath 被廣泛用於從 API 回應中擷取值、驗證資料,以及建立動態測試斷言。快速開始#
1
JSON 回應範例
假設我們有以下 JSON 回應:
{
"store": {
"book": [
{ "category": "fiction", "author": "Author A", "title": "Book 1" },
{ "category": "reference", "author": "Author B", "title": "Book 2" },
{ "category": "fiction", "author": "Author C", "title": "Book 3" }
]
}
}
2
擷取資料
若要擷取陣列中第一本
book 的
title,請使用此 JSONPath 表達式:
3
JSONPath 表達式說明
讓我們拆解表達式
$.store.book[0].title:
$:指 JSON 文件的根節點,也就是整個結構本身。
store:指向 store 屬性,它是根節點下的一個物件。
book:存取 store 物件下的 book 屬性,該屬性是一個陣列。
[0]:選取 book 陣列中的第一個元素(索引從 0 開始)。
總結來說,此表達式會從根節點開始導覽,找到 store 物件,存取 book 陣列,選取第一個項目,並擷取該項目的 title。JSONPath 中的字串必須使用單引號,例如:$.store.book[?(@.category=='reference')]。
語法概覽#
基本語法#
| 語法 | 說明 |
|---|
$ | 根節點 |
@ | 目前節點 |
.node or ['node'] | 存取子節點 |
[index] | 陣列索引,支援從 0 開始計數 |
[start:end:step] | 陣列切片 |
* | 萬用字元,符合所有子節點 |
.. | 遞迴萬用字元,符合所有後代節點 |
(<expr>) | 動態表達式 |
?(<boolean expr>) | 篩選條件 |
擴充語法#
| 語法 | 說明 |
|---|
^ | 存取符合項目的父層 |
~ | 取得符合項目的屬性名稱(以陣列形式) |
@null(), @boolean(), @number(), @string(), @array(), @object() | 擷取基本 JSON 型別 |
@integer() | 擷取整數型別 |
@scalar() | 擷取複合型別,可接受 undefined 和非有限數值(查詢 JavaScript 物件時) |
@other() | 可與使用者定義的 otherTypeCallback 搭配使用 |
@undefined(), @function(), @nonFinite() | 查詢非 JSON JavaScript 物件時使用的非 JSON 型別 |
@path, @parent, @property, @parentProperty, @root | 篩選器中的簡寫選擇器 |
` | 跳脫剩餘序列 |
@['...'], ?@['...'] | 在篩選器中跳脫屬性名稱裡的特殊字元 |
$.. | 擷取所有父層元件 |
JSONPath 範例#
以下是一些基於範例 JSON 資料的常見 JSONPath 表達式:範例 JSON 資料#
{
"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 | 結果 |
|---|
/store/book/author | $.store.book[*].author | 所有書籍的作者 |
//author | $..author | 所有作者 |
/store/* | $.store.* | store 下的所有子節點 |
/store//price | $.store..price | 所有 price 欄位 |
//book[3] | $..book[2] | 第三本書(以 0 為基準的索引) |
//book[last()] | $..book[(@.length-1)] or $..book[-1:] | 最後一本書 |
//book[position()<3] | $..book[:2] or $..book[0,1] | 前兩本書 |
//book[isbn] | $..book[?(@.isbn)] | 具有 ISBN 的書籍 |
//book[price<10] | $..book[?(@.price<10)] | 價格低於 10 的書籍 |
//* | $..* | 遞迴符合所有子節點 |
Apidog 中的使用案例#
JSONPath 在 Apidog 中特別適用於:回應驗證:從 API 回應中擷取特定值以驗證正確性
資料擷取:從複雜的巢狀 JSON 結構中提取特定欄位
參考資料#
Modified at 2026-06-11 10:26:02