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

93 views Asked by At

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

  • Before 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
            } 
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

  • After JSON (I want this result)
{
    "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?

1

There are 1 answers

1
wp78de On BEST ANSWER

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.