Search code examples
javajsonpath

JsonPath - cache the JSON and then perform multiple queries?


I have inherited some code that does a lot of JsonPath queries against a single JSON file. For each query it passes in the JSON file and the query. This then becomes a call to JsonPath.read(jsonFile, jpathQuery).

Is there a way to avoid having it build up whatever internal structure it needs of the JSON to then perform the query? Is there a way to have it build up the internal model of the JSON once and then perform multiple queries against it?

thanks - dave


Solution

  • I'm assuming you are using this jsonpath library.

    In their docs they have this

    The simplest most straight forward way to use JsonPath is via the static read API.

    String json = "...";
    List<String> authors = JsonPath.read(json, "$.store.book[*].author");
    

    If you only want to read once this is OK. In case you need to read an other path as well this is not the way to go since the document will be parsed every time you call JsonPath.read(...). To avoid the problem you can parse the json first.

    String json = "..."; Object document =
    Configuration.defaultConfiguration().jsonProvider().parse(json);
    String author0 = JsonPath.read(document, "$.store.book[0].author");
    String author1 = JsonPath.read(document, "$.store.book[1].author");