Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble composing jsonpath query to return first object of a filtered array

Tags:

jsonpath

Using the ashphy json path evaluator, and the following 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
      },
      { "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 would like to write a query that filters category, e.g. "fiction", and then return only the first element. I can't quite seem to figure it out.

For example, $..book[?(@.category == "fiction")], will return an array of 3 books, but I just want the first book:

{ "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }

Can it be done?? The obvious thing seemed to be to add an "[0]" to the end, but it does not work.

like image 879
Blazes Avatar asked Jan 22 '15 17:01

Blazes


1 Answers

I examined the analytics site (Note: this is from testing http://ashphy.com/JSONPathOnlineEvaluator/):

enter image description here

Placing the [0] index look up DOES work. The site merely accepts what will go inside the argument of jsonPath(jsonObj, query string) thus the index reference must go outside this evaluation which the site does not do.

jsonPath(foo, '$..book[?(@.category == "fiction")]')[0]
like image 89
Diniden Avatar answered Oct 23 '22 07:10

Diniden