在 JsonPath 中,[<number> (, <number>)] 操作符用于获取数组中指定的多个索引位置的节点。假如存在如下 JSON:
{ "books": [{"title":"title1"}, {"title":"title2"}, {"title":"title3"}, {"title":"title4"}] }
如果使用“$.books[0,1]”JsonPath 表达式将返回 {"title":"title1"} 和 {"title":"title2"} 元素。
Java 示例:
package com.hxstrive.json_path.operators; import com.jayway.jsonpath.JsonPath; /** * [index,index,...] 符号 * @author hxstrive.com */ public class OperatorsDemo07 { public static void main(String[] args) { String 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" + " }" + " }," + " \"expensive\": 10" + "}"; Object obj = JsonPath.read(json, "$.store.book[0,1]"); System.out.println(obj); } }
运行示例,输出如下:
[{"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}]
上述示例,将获取 JSON 中 book 中下标为 0 和 1 的书籍。