[英]JSON Path extract specific fields/array from parent and child object using JSON Path
給定一個JSON對象,例如:
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"book_id": "214515",
"title": "Sayings of the Century",
"price": 8.95,
"reviews": [
{
"rating": 2,
"reviewer": "Amazon",
"weight": 0
},
{
...
}
]
},
{
...
}
是否可以選擇book_id以及該書的部分或全部評論?
結果可能如下所示:
[
{
"book_id": "...",
"reviews": [
...
]
},
{
...
}
]
我一直在使用Jayway jsonpath: https : //github.com/json-path/JsonPath
在處理數組(例如“評論”)然后以編程方式加入時,以下不適合作為解決方案:
List ids = JsonPath.read(json, "$.store.books[*].book_id");
List reviews = JsonPath.read(json, "$.store.books[*].reviews[*]");
遵循https://github.com/json-path/JsonPath
的文檔,這應該可以為您提供所需的內容。
List output = JsonPath.read(json, "$.books[*].['book_id', 'reviews'])");
看一下這個測試用例。
@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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.