การวิเคราะห์ข้อมูล JSON
เมื่อโหลดแคตาล็อกสินค้าเรียบร้อยแล้ว ทีมการตลาดได้ขอรายงานด้านราคา โดยต้องการทราบราคาเฉลี่ย ระบุสินค้าที่แพงที่สุด และดูการกระจายตัวของสินค้าในแต่ละหมวดหมู่
ข่าวดีคือ เมื่อข้อมูล JSON อยู่ในตาราง Tablesaw แล้ว สามารถใช้การดำเนินการกับคอลัมน์แบบเดิมที่คุ้นเคยได้เลย
คลาส JsonReader, JsonReadOptions และ Table ถูก import ไว้แล้ว และไฟล์ products.json มีคอลัมน์ name, price และ category
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การนำเข้าข้อมูลใน Java
คำแนะนำการฝึกหัด
- เติมโค้ดการอ่าน JSON ให้สมบูรณ์เพื่อโหลดตารางสินค้า
- คำนวณราคาเฉลี่ยโดยใช้เมธอดของคอลัมน์
- หาราคาสูงสุดในชุดข้อมูล
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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());
}
}