Importing Data in Java
Anthony Markham
VP Quant Developer

| Name | Age | City |
|-------|-----|---------|
| Alice | 30 | Boston |
| Bob | 25 | Seattle |
[
{"name": "Alice",
"age": 30,
"address": {"city": "Boston",
"state": "MA"}},
{"name": "Bob",
"age": 25,
"address": {"city": "Seattle",
"state": "WA"}}
]
// 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);
Tablesaw methods work// 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);
// 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");
}
// Remove rows with any missing values
data = data.dropRowsWithMissingValues();
// Convert integer column to double for calculations
data = data.replaceColumn("price", data.intColumn("price").asDoubleColumn());
Importing Data in Java