0
votes

I would like to extract an element based on a condition inside a nested JSON response. Using the widely searched example below, I would like to extract the storeid of all books authored by "Foo Bar":

{
    "store": {
        "storeId": 1
        "book": [
            {
                "category": "reference",
                "author": [
                      {
                       "Nigel Rees",
                       "Foo Bar"
                      }
                ],
                "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
}

I have tried using expressions like: $.store[?(@..author=='Foo Bar')].storeId

I have also tried to see if there are any store returned at all using: $.store[*].book[?(@.author=='Foo Bar')]

But no result returned... Please help. Thanks!

1

1 Answers

0
votes

What you produced is not a valid JSON so you won't be able to use JSON Extractor on it.

If you amend this good example which you cannot even properly copy and paste to include your storeId:

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

You will be able to extract the storeId where one of the authors is Nigel Rees using the following expression:

$.store[?(@.book[?(@.author=="Nigel Rees")])].storeId

Demo:

enter image description here

More information: