在不知道处理的是对象还是数组时使用 JsonPath

Using JsonPath when you don't know if you're dealing with an object or array

给出以下 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
}

我们可以使用像 $.store.book[*].author 这样的路径表达式来获取所有作者。但是如果我们事先不知道 book 是一个数组还是一个对象呢?如果我们可以拥有上面的 JSON 但也可以是这样的:

{
    "store": {
        "book": {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
        },
        "bicycle": {
            "color": "red",
            "price": 19.95
         }
    },
    "expensive": 10
}

是否有 "generic path" 可用于在任一情况下获取所有作者?

是的,您可以使用:

$.store..author

可在此处测试:

https://jsonpath.curiousconcept.com/

'希望对您有所帮助。