Read JSON/YAML
Read JSON or YAML file and optionally extract nested array
Source Code
import fs from "fs";
import path from "path";
import YAML from "yaml";
const [inputPath, arrayPath = "", outputPath] = process.argv.slice(2);
if (!inputPath || !outputPath) {
console.error("Usage: inputPath [arrayPath] outputPath");
process.exit(1);
}
/**
* Get nested value using dot notation
*/
function getPath(obj, dotPath) {
if (!dotPath) return obj;
const parts = dotPath.split(".");
let value = obj;
for (const part of parts) {
if (value == null) return undefined;
value = value[part];
}
return value;
}
try {
console.log(`Reading ${inputPath}...`);
const raw = fs.readFileSync(inputPath, "utf-8");
// Detect format by extension or content
const ext = path.extname(inputPath).toLowerCase();
let data;
if (ext === ".yaml" || ext === ".yml") {
console.log(" Parsing as YAML...");
data = YAML.parse(raw);
} else if (ext === ".json") {
console.log(" Parsing as JSON...");
data = JSON.parse(raw);
} else {
// Try JSON first, then YAML
try {
data = JSON.parse(raw);
console.log(" Parsed as JSON");
} catch {
data = YAML.parse(raw);
console.log(" Parsed as YAML");
}
}
// Extract nested path if specified
let result = data;
if (arrayPath) {
console.log(` Extracting path: ${arrayPath}`);
result = getPath(data, arrayPath);
if (result === undefined) {
console.error(`Path "${arrayPath}" not found in data`);
process.exit(1);
}
}
// Ensure output directory exists
const dir = path.dirname(outputPath);
if (dir && dir !== ".") {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(outputPath, JSON.stringify(result, null, 2));
const itemCount = Array.isArray(result) ? result.length : 1;
const isArray = Array.isArray(result);
console.log(`\nā Read and converted ${inputPath}`);
console.log(` Type: ${isArray ? `array (${itemCount} items)` : typeof result}`);
if (arrayPath) {
console.log(` Extracted path: ${arrayPath}`);
}
console.log(` Written to: ${outputPath}`);
console.log(
JSON.stringify({
success: true,
inputPath,
outputPath,
arrayPath: arrayPath || null,
isArray,
itemCount: isArray ? itemCount : null,
})
);
} catch (error) {
console.error("Error:", error.message);
process.exit(1);
}