Given a JSON object like:
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"book_id": "214515",
"title": "Sayings of the Century",
"price": 8.95,
"reviews": [
{
"rating": 2,
"reviewer": "Amazon",
"weight": 0
},
{
...
}
]
},
{
...
}
Is it at all possible to select book_id, along with part or all of the reviews for that book?
The result might look something like this:
[
{
"book_id": "...",
"reviews": [
...
]
},
{
...
}
]
I've been using Jayway jsonpath: https://github.com/json-path/JsonPath
The following is not suitable a solution when dealing with arrays, like the 'reviews', and then joining programmatically:
List ids = JsonPath.read(json, "$.store.books[*].book_id");
List reviews = JsonPath.read(json, "$.store.books[*].reviews[*]");
Following the doc at https://github.com/json-path/JsonPath
, this should give you what you are looking for.
List output = JsonPath.read(json, "$.books[*].['book_id', 'reviews'])");
Have a look at this test case.
@Test
final void test2() {
String json = "{ \"books\": ["
+ " {"
+ " \"category\": \"reference\","
+ " \"author\": \"Nigel Rees\","
+ " \"book_id\": \"214515\","
+ " \"title\": \"Sayings of the Century\","
+ " \"price\": 8.95,"
+ " \"reviews\": ["
+ " {"
+ " \"rating\": 2,"
+ " \"reviewer\": \"Amazon\","
+ " \"weight\": 0"
+ " }"
+ " ]"
+ " },"
+ " {"
+ " \"category\": \"reference\","
+ " \"author\": \"Nigel Rees\","
+ " \"book_id\": \"314515\","
+ " \"title\": \"Sayings of the Century\","
+ " \"price\": 8.95,"
+ " \"reviews\": ["
+ " {"
+ " \"rating\": 4,"
+ " \"reviewer\": \"Trip\","
+ " \"weight\": 5"
+ " }"
+ " ]"
+ " }"
+ " ]"
+ "}";
List output = JsonPath.read(json, "$.books[*].['book_id', 'reviews'])");
String expectedOutput =
"["
+ "{"
+ "\"book_id\":\"214515\","
+ "\"reviews\":["
+ "{"
+ "\"rating\":2,\"reviewer\":\"Amazon\",\"weight\":0"
+ "}"
+ "]"
+ "},"
+ "{"
+ "\"book_id\":\"314515\","
+ "\"reviews\":["
+ "{\"rating\":4,\"reviewer\":\"Trip\",\"weight\":5}"
+ "]"
+ "}"
+ "]";
assertEquals(expectedOutput, output.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.