-
Notifications
You must be signed in to change notification settings - Fork 1
JSONPath
xmljim edited this page Feb 13, 2021
·
1 revision
JSON-JEP integrates the Jayway JsonPath implementation to natively work with the JSON-JEP API. There are two ways to execute a JsonPath query:
- Using the
JSONPathFactoryto compile and create aJSONPathinstance - Using the
select*()functions on either theJSONObjectorJSONArrayinterfaces.
The JSONPathFactory allows you to create a JSONPath instance by compiling a JSONPath expression, then executing the query against a JSONNode instance (either a JSONObject or JSONArray). Once the JSONPath instance is created, you can execute a query using one of the select* methods:
-
JSONArray select(JSONNode context): apply the compiled JsonPath query to the current JSONNode. Returns a JSONArray of zero or more results -
<T> T selectValue(JSONNode context): Return a typed value from the query
The JSONPathFactory includes two methods:
static JSONPath compile(String jsonPath, Option... options)static JSONPath compile(String jsonPath, Criteria criteria, Option...options)
The following is an example of using the JSONPathFactory
/*
JSONObject obj = ... (see the Getting Started page for how to initialize a JSONObject
*/
JSONPath jsonPath = JSONPathFactory.compile("$.store.book[*].author");
JSONArray results = jsonPath.select(obj);
results.spliterator()... //stream out the values;Likewise, you can get a single value using the selectValue(JSONNode) context:
JSONPath jsonPath = JSONPathFactory.compile("$.store.book[0].author");
String author = jsonPath.selectValue(obj);The JSONNode interface includes several select* methods which assumes that the current node is the context from which to apply the JsonPath query.
final JSONNode node = ParserFactory.getParser().parse(getClass().getResourceAsStream("/us-reps.json"));
final JSONArray dems = node.select("$.objects[?(@.party=='Democrat')]");
final JSONArray gop = node.select("$.objects[?(@.party=='Republican')]");
JSONObject jaredPolis = dems.selectValue("$.*[?(@.person.lastname=='Polis')]");
System.out.println(jaredPolis.prettyPrint());