Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save brandonhimpfen/ceba8f0df427858bac91d745cf42fba2 to your computer and use it in GitHub Desktop.

Select an option

Save brandonhimpfen/ceba8f0df427858bac91d745cf42fba2 to your computer and use it in GitHub Desktop.
Infer a simple schema shape from JSONL/NDJSON sample rows in Node.js while streaming, with no dependencies.
#!/usr/bin/env node
/**
* Infer a simple schema shape from JSONL sample rows.
*
* Usage:
* cat input.jsonl | node node-infer-jsonl-schema-shape.js
* cat input.jsonl | node node-infer-jsonl-schema-shape.js --limit=1000
*
* Output:
* A JSON schema-like shape showing observed field types.
*/
const readline = require("readline");
function parseArgs(argv) {
const args = {
limit: 1000,
};
for (const arg of argv.slice(2)) {
if (arg.startsWith("--limit=")) {
args.limit = Number(arg.split("=", 2)[1]);
continue;
}
if (arg === "-h" || arg === "--help") {
args.help = true;
continue;
}
throw new Error(`Unknown argument: ${arg}`);
}
return args;
}
function usage() {
console.error(`Usage: cat input.jsonl | node node-infer-jsonl-schema-shape.js [--limit=N]
Options:
--limit=N Maximum number of records to inspect (default: 1000)
`);
}
function typeOf(value) {
if (Array.isArray(value)) return "array";
if (value === null) return "null";
return typeof value;
}
function mergeType(existing, next) {
if (!existing) return next;
if (existing === next) return existing;
const types = new Set();
for (const t of String(existing).split("|")) types.add(t);
for (const t of String(next).split("|")) types.add(t);
return [...types].sort().join("|");
}
function inferValue(value) {
const t = typeOf(value);
if (t === "object") {
const shape = {};
for (const [key, child] of Object.entries(value)) {
shape[key] = inferValue(child);
}
return shape;
}
if (t === "array") {
if (value.length === 0) return [];
let itemShape = null;
for (const item of value) {
itemShape = mergeShape(itemShape, inferValue(item));
}
return [itemShape];
}
return t;
}
function mergeShape(a, b) {
if (a == null) return b;
if (b == null) return a;
if (typeof a === "string" && typeof b === "string") {
return mergeType(a, b);
}
if (Array.isArray(a) && Array.isArray(b)) {
return [mergeShape(a[0], b[0])];
}
if (
typeof a === "object" &&
typeof b === "object" &&
!Array.isArray(a) &&
!Array.isArray(b)
) {
const out = { ...a };
for (const [key, value] of Object.entries(b)) {
out[key] = mergeShape(out[key], value);
}
return out;
}
return mergeType(shapeType(a), shapeType(b));
}
function shapeType(shape) {
if (Array.isArray(shape)) return "array";
if (typeof shape === "object" && shape !== null) return "object";
return String(shape);
}
async function main() {
const args = parseArgs(process.argv);
if (args.help) {
usage();
process.exit(0);
}
if (!Number.isInteger(args.limit) || args.limit <= 0) {
throw new Error("--limit must be a positive integer");
}
const rl = readline.createInterface({
input: process.stdin,
crlfDelay: Infinity,
});
let inferred = null;
let inspected = 0;
let lineNum = 0;
for await (const line of rl) {
lineNum += 1;
if (!line.trim()) continue;
let record;
try {
record = JSON.parse(line);
} catch (err) {
throw new Error(`Invalid JSON on line ${lineNum}: ${err.message}`);
}
inferred = mergeShape(inferred, inferValue(record));
inspected += 1;
if (inspected >= args.limit) break;
}
console.error(`Inspected records: ${inspected}`);
console.log(JSON.stringify(inferred ?? {}, null, 2));
}
main().catch((err) => {
console.error("ERROR:", err && err.stack ? err.stack : err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment