พื้นฐานข้อมูล JSON กับ Tablesaw

การนำเข้าข้อมูลใน Java

Anthony Markham

VP Quant Developer

แนะนำ JSON

  • JSON: JavaScript Object Notation
    • รูปแบบแลกเปลี่ยนข้อมูลที่มีขนาดเบา
    • รูปแบบมาตรฐานของ Web API
    • โครงสร้างแบบ key-value pair

ภาพตัวอย่าง JSON

การนำเข้าข้อมูลใน Java

ข้อมูลแบบตาราง

  • แถวและคอลัมน์คงที่
  • ตาราง: ชนิดข้อมูลสม่ำเสมอ
| Name  | Age | City    |
|-------|-----|---------|
| Alice | 30  | Boston  |
| Bob   | 25  | Seattle |

JSON

  • โครงสร้างซ้อนกันที่ยืดหยุ่น
  • รองรับชนิดข้อมูลและลำดับชั้นที่หลากหลาย
[
  {"name": "Alice", 
      "age": 30, 
      "address": {"city": "Boston", 
                  "state": "MA"}},
  {"name": "Bob", 
      "age": 25, 
      "address": {"city": "Seattle", 
                  "state": "WA"}}
]
การนำเข้าข้อมูลใน Java

การอ่านไฟล์ JSON

  • ใช้กับไฟล์ JSON แบบง่ายเท่านั้น
// Simple method to read a JSON file
Table products = Table.read().file("products.json");

$$

import tech.tablesaw.io.json.JsonReader;
import tech.tablesaw.io.json.JsonReadOptions;
  • รองรับการกำหนดค่าเพิ่มเติม
// Reading a JSON file using JsonReadOptions
JsonReadOptions options = JsonReadOptions.builder("products.json").build();

Table products = new JsonReader().read(options);
การนำเข้าข้อมูลใน Java

การเข้าถึงข้อมูล JSON

  • ใช้เมธอด Tablesaw ที่คุ้นเคยได้เลย
// Access columns from JSON data
StringColumn names = table.stringColumn("name");
DoubleColumn prices = table.doubleColumn("price");

// Perform calculations double avgPrice = prices.mean(); String mostExpensive = table .where(prices.isEqualTo(prices.max())) .stringColumn("name").get(0);
การนำเข้าข้อมูลใน Java

แนวทาง JSON ที่ดี - การตรวจสอบความถูกต้อง

  • ตรวจสอบโครงสร้าง JSON ก่อนประมวลผล
// Validation and error handling
try {
    JsonReadOptions options = JsonReadOptions.builder("data.json").build();
    Table data = new JsonReader().read(options);
    if (data.rowCount() > 0) {
        // Process data
    }
} catch (Exception e) {
    System.err.println("Error reading JSON: " + e.getMessage());
}
if (data.rowCount() == 100) {
    System.out.println("Table has exactly 100 rows - processing data");
}
การนำเข้าข้อมูลใน Java

แนวทาง JSON ที่ดี - ค่าที่หายไป

  • จัดการค่าที่หายไป/null
// Remove rows with any missing values
data = data.dropRowsWithMissingValues();
  • ปรับชนิดข้อมูลให้เหมาะกับการวิเคราะห์
// Convert integer column to double for calculations
data = data.replaceColumn("price", data.intColumn("price").asDoubleColumn());
การนำเข้าข้อมูลใน Java

มาฝึกกันเถอะ!

การนำเข้าข้อมูลใน Java

Preparing Video For Download...