如何通过JSONPath

时间:2017-03-30 18:39:42

标签: java jsonpath

我正在编写一个JSONPath表达式,该表达式在对象的一个​​字段进行过滤时对数组中的对象进行计数。

输入取自http://jsonpath.herokuapp.com/

的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
}

我的表达式提取对象" category"是"小说"。

$.store.book[?(@.category == "fiction")]

输出符合预期。

[
   {
      "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
   }
]

到目前为止一切顺利。我想要实现的是计算数组中的对象数量。在这种情况下3.我尝试了这个表达式:

$.store.book[?(@.category == "fiction")].length()

输出不是我的预期。

[
   4,
   5,
   5
]

以下没有工作

$.store[?(@.book[*].category == "fiction")].length()

如何计算数组中的元素数量?如果我使用jq,则可以将其写为

[.store.book[] | select (.category == "fiction")] | length

0 个答案:

没有答案