JSON(JavaScript Object Notation)是一种轻量级、基于文本的数据交换格式,易于人阅读和编写,也易于机器解析和生成。它使用键值对、对象({}
)和数组([]
),支持六种数据类型:字符串、数字、布尔值、数组、对象和空值。JSON 广泛用于 API 和配置文件,独立于语言,被大多数编程语言支持。
{
"name": "JavaScript",
"creator": "Brendan Eich",
"year": 1995,
"extensions": [".js", ".mjs"]
}
以下是来自 Stefan Goessner's original post 在 2007 年介绍 JSONPath 的语法和示例。
JSONPath | 描述 |
---|---|
$ | 根对象/元素 |
@ | 当前对象/元素 |
. | 子成员操作符 |
.. | 递归后代操作符; JSONPath 从 E4X 借用此语法 |
* | 通配符匹配所有对象/元素,不考虑名称 |
[] | 下标操作符 |
[,] | 用于交替名称或数组索引的联合操作符 |
[start:end:step] | 从 ES4 / Python 借用的数组切片操作符 |
?() | 通过静态评估应用过滤(脚本)表达式 |
() | 通过静态评估应用脚本表达式 |
以下是给定示例数据集的示例表达式:
{
"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
}
}
}
JSONPath | 描述 |
---|---|
$.store.book[*].author | 商店中所有书籍的作者 |
$..author | 所有作者 |
$.store.* | 商店中所有物品,包括一些书籍和一辆红色自行车 |
$.store..price | 商店中所有物品的价格 |
$..book[2] | 第三本书 |
$..book[(@.length-1)] | 通过脚本下标获取最后一本书 |
$..book[-1:] | 通过切片获取最后一本书 |
$..book[0,1] | 通过下标联合获取前两本书 |
$..book[:2] | 通过下标数组切片获取前两本书 |
$..book[?(@.isbn)] | 过滤所有带有 ISBN 号的书籍 |
$..book[?(@.price<10)] | 过滤所有价格低于 10 元的书籍 |
$..book[?(@.price==8.95)] | 过滤所有价格为 8.95 元的书籍 |
$..book[?(@.price<30 && @.category=="fiction")] | 过滤所有价格低于 30 元且分类为 “fiction” 的书籍 |
$..* | JSON 结构中的所有成员 |
JSON.parse
将 JSON 字符串转换为对象,使用 JSON.stringify
将对象转换回 JSON。