Skip to content

Working with JSON tables in TypeScript

JSON file handling with automatic format detection and high-performance data operations.

Terminal window
npm install fairspec

The JSON plugin provides:

  • loadJsonTable - Load JSON files into tables
  • saveJsonTable - Save tables to JSON files
  • JsonPlugin - Plugin for framework integration

For example:

import { loadJsonTable } from "fairspec"
const table = await loadJsonTable({ data: "table.json" })
// Standard JSON array of objects format
import { loadJsonTable } from "fairspec"
// Load from local file
const table = await loadJsonTable({ data: "data.json" })
// Load from remote URL
const table = await loadJsonTable({
data: "https://example.com/data.json"
})
// Load multiple files (concatenated)
const table = await loadJsonTable({
data: ["file1.json", "file2.json"]
})
import { saveJsonTable } from "fairspec"
// Save with default options
await saveJsonTable(table, { path: "output.json" })
// Save with explicit format
await saveJsonTable(table, {
path: "output.json",
format: { name: "json" }
})

JSON tables use an array of objects format:

[
{"id": 1, "name": "Alice", "age": 30},
{"id": 2, "name": "Bob", "age": 25}
]

Extract data from nested objects using jsonPointer:

// Input: {"users": [{"id": 1, "name": "Alice"}]}
const table = await loadJsonTable({
data: "data.json",
format: {
name: "json",
jsonPointer: "users"
}
})

Select specific columns using columnNames:

// Only load specific columns
const table = await loadJsonTable({
data: "data.json",
format: {
name: "json",
columnNames: ["name", "age"]
}
})

Handle CSV-style array data with rowType: "array":

// Input: [["id", "name"], [1, "Alice"], [2, "Bob"]]
const table = await loadJsonTable({
data: "data.json",
format: {
name: "json",
rowType: "array"
}
})

Wrap data in a nested structure when saving:

// Output: {"users": [{"id": 1, "name": "Alice"}]}
await saveJsonTable(table, {
path: "output.json",
format: {
name: "json",
jsonPointer: "users"
}
})