jsonjsonpathjayway

How to get the whole json with the result reflected after filter by string using JsonPath


Can I get the whole json with the result reflected after filter by string using JsonPath?

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

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

Filter by string for book is done through '$..book[?(@.author =~ /.*REES/i)]'

but can you tell me to get the whole JSON reflected?


Solution

  • You cannot do this using JSONPath; while you want to select the outer-most item based on inner items property, you do not want to retrieve the outer item as a whole. That does not work.

    Selecting the outer item can be done like this

    $..store[?(@.book[0].author =~ /.*REES/i)]
    

    but this will also return the book at position 2, i.e. index 1.

    It sounds like you actually need a JSON transformation like Jolt.

    For instance, Jolt's remove transformer would allow you to to remove the second book like this:

    [
      {
        "operation": "remove",
        "spec": {
          "store": {
            "book": {
              "array": {
                "1": "" //remove book at position 2
              }
            }
          }
        }
      }
    ]
    

    Try it online with your own input here.