Home > Blockchain >  How to filter an array and get the filtered length?
How to filter an array and get the filtered length?

Time:03-22

Use the typical json as an example:

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

I want filter the books, and get the filter result array size.

I write the json path as: $..book[?(@.category in ['fiction'])].size()

The expected value is 3. But actually I got 14.

Tried $..book[?(@.category in ['fiction'])].length()

Still got same result: 14

CodePudding user response:

Why don't you use something like this:

int count = 0;
for (Book book : store) {
  count = book.category.equals('fiction')? count 1 : count;
}

CodePudding user response:

You need to use:

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

Many examples in: https://www.npmjs.com/package/jsonpath

  • Related