A High-Performance JSONPath Engine for MoonBit ecosystem
moon add ppyj663/jsonpath{
"import": [
"ppyj663/jsonpath"
]
}let json_str =
#|{
#| "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 }
#| ],
#| "bicycle": { "color": "red", "price": 19.95 }
#| }
#|}
// 1. 将字符串解析为 @json.Json 类型
let json = @json.parse!(json_str)
// 2. 使用 JSONPath 查询数据
match @jsonpath.query(json, "$.store.book[0].title") {
Ok(res) => {
// res 类型为 Array[Json]
println("找到 \{res.length()} 个匹配项:")
println(res[0]) // 输出: Json::String("Sayings of the Century")
}
Err(e) => println("解析或查询出错: \{e}")
}| 语法标识 | 描述 | 示例 |
|---|---|---|
| $ | 根节点,所有查询的起始位置。 | $ |
| .<name> | 访问对象中的指定字段。 | $.store.bicycle |
| ['<name>'] | 访问对象中的指定字段(适用于带特殊字符的键名)。 | $['store']['book'] |
| .. | 递归搜索当前树下的所有匹配节点。 | $..price |
| .* / [*] | 通配符,匹配所有字段或数组元素。 | $.store.book[*] |
| [<number>] | 通过数组下标访问元素。 | $..book[1] |
let all_prices = @jsonpath.query(json, "$..price").unwrap()let all_books = @jsonpath.query(json, "$.store.book[*]").unwrap()A High-Performance JSONPath Engine for MoonBit ecosystem