Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON PATH Field NULL Checking Expression

I have a json array like bellow :

{
"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,
            "likes": 1
        },
        {
            "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}

I was trying to find all books price which have no likes field. Is it possible to find using Jayway Json Path library. I am trying something like this $.store.book[? (@.likes == null)].price but i don't know whether there is anything like that?

like image 366
Yassir Arafat Roni Avatar asked Jan 05 '18 07:01

Yassir Arafat Roni


1 Answers

This jsonpath expression is correct:

$.store.book[?(@.likes == null)].price

But you must set DEFAULT_PATH_LEAF_TO_NULL, for example:

Configuration conf = Configuration.defaultConfiguration()
    .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);

String pricesForBooksWithNoLikes = JsonPath.using(conf).parse(json)
    .read("$.store.book[?(@.likes == null)].price");

More details in the docs.

Here's a screenshot showing this read working, using the Jayway JsonPath Evaluator:

enter image description here

like image 69
glytching Avatar answered Oct 12 '22 00:10

glytching