JSON 資料分析
產品型錄已載入,行銷團隊要求產出一份定價報告。他們想知道平均價格、找出最昂貴的產品,並查看各品類的產品分布。
好消息是:一旦把 JSON 資料放進 Tablesaw 的資料表,你就能使用已經熟悉的同一套欄位操作。
JsonReader、JsonReadOptions 與 Table 類別都已匯入,products.json 檔案包含 name、price、category 欄位。
本練習屬於課程
Java 中的資料匯入
練習說明
- 完成 JSON 讀取以載入 products 資料表。
- 使用欄位方法計算平均價格。
- 找出資料集中最高的價格。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class JSONAnalysis {
public static void main(String[] args) {
// Complete the JSON read
JsonReadOptions options = JsonReadOptions.builder("products.json").build();
Table products = new JsonReader().____(options);
// Calculate average price
double avgPrice = products.doubleColumn("price").____();
// Find maximum price
DoubleColumn priceCol = products.doubleColumn("price");
double maxPrice = ____.____();
String mostExpensive = products
.where(priceCol.isEqualTo(maxPrice))
.stringColumn("name").get(0);
Table categoryCount = products.countBy("category");
System.out.println("Product Analytics Report:");
System.out.println("========================");
System.out.printf("Average Price: $%.2f%n", avgPrice);
System.out.println("Most Expensive: " + mostExpensive + " ($" + maxPrice + ")");
System.out.println("\nCategory Distribution:");
System.out.println(categoryCount.print());
}
}