使用 Tablesaw 的 JSON 資料基礎

Java 中的資料匯入

Anthony Markham

VP Quant Developer

JSON 簡介

  • JSON:JavaScript Object Notation
    • 輕量級資料交換格式
    • Web API 標準格式
    • 鍵值配對結構

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...