JsonPath keys() 函数:获取节点下的键集合

在 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]


说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号