I have nested json data, like so:
{ "libraries":[ { "State":"California", "genres":[ { "genre":"thriller", "books":[ { "title":"Book 1" }, { "title":"Book 2" } ] }, { "genre":"mystery", "books":[ { "title":"Book 2" }, { "title":"Book 3" } ] } ] }, { "State":"New York", "genres":[ { "genre":"horror", "books":[ { "title":"Book 2" }, { "title":"Book 5" } ] }, { "genre":"comedy", "books":[ { "title":"Book 6" }, { "title":"Book 7" } ] } ] } ] }
And I am using the jayway jsonpath library in Scala to parse it.
I could use something like JsonPath.read(myData,"$.libraries[*].genres[*].books[*]")
to get an array of all the books pooled from every library. What I want is to know the path for each book, e.g. "$.libraries(0).genres(1).books(0)"
. Is there a ways to get an array of all the book paths rather than just all the books?
I am new to jsonpaths in general, so forgive me if this is not a good question.
Advertisement
Answer
You can use configuration with Option.AS_PATH_LIST
:
val conf = Configuration.builder.options(Option.AS_PATH_LIST).build val paths = JsonPath.parse(json, conf).read[JSONArray]("$.libraries[*].genres[*].books[*]") for(path <- paths.toArray){ println(path.toString) }
Which gives in case of your example json:
$['libraries'][0]['genres'][0]['books'][0] $['libraries'][0]['genres'][0]['books'][1] $['libraries'][0]['genres'][1]['books'][0] $['libraries'][0]['genres'][1]['books'][1] $['libraries'][1]['genres'][0]['books'][0] $['libraries'][1]['genres'][0]['books'][1] $['libraries'][1]['genres'][1]['books'][0] $['libraries'][1]['genres'][1]['books'][1]