在 Jayway JSONPath 中,keys() 函数并不是标准 JSONPath 规范的一部分,keys() 函数用来返回 JsonPath 表达式返回的当前节点的所有直接键集合。例如:
$.store.bicycle.keys()
上述 JsonPath 仅仅返回 bicycle 节点下的键集合。
Java 示例:
package com.hxstrive.json_path.function;
import com.jayway.jsonpath.JsonPath;
/**
* keys() 函数
* @author hxstrive.com
*/
public class FunctionDemo07 {
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" +
" }" +
" ]," +
" \"bicycle\": {" +
" \"color\": \"red\"," +
" \"price\": 19.95" +
" }" +
" }," +
" \"expensive\": 10" +
"}";
Object obj = JsonPath.read(json, "$.keys()");
System.out.println(obj); // [store, expensive]
obj = JsonPath.read(json, "$.store.keys()");
System.out.println(obj); // [book, bicycle]
obj = JsonPath.read(json, "$.store.bicycle.keys()");
System.out.println(obj); // [color, price]
obj = JsonPath.read(json, "$.store.book[0].keys()");
System.out.println(obj); // [category, author, title, price]
obj = JsonPath.read(json, "$.store.book[*].keys()");
System.out.println(obj); // [["category","author","title","price"],["category","author","title","price"]]
obj = JsonPath.read(json, "$..bicycle.keys()");
System.out.println(obj); // [store, expensive] 注意
}
}运行示例,输出如下:
[store, expensive] [book, bicycle] [color, price] [category, author, title, price] [["category","author","title","price"],["category","author","title","price"]] [store, expensive]