A tiny, zero-dependency TypeScript utility to read JSON files safely.
npm install ts-simple-json-readerimport { readJson, readJsonSync, isJsonObject, isJsonArray } from "ts-simple-json-reader";
const data = readJsonSync("./package.json");
if (isJsonObject(data)) {
console.log(Object.keys(data));
}
const main = async () => {
const value = await readJson("./tsconfig.json");
if (isJsonArray(value)) {
console.log(value.length);
}
};
main();npx ts-simple-json-reader ./data/sample.json- readJsonSync(path, options?) reads and parses a JSON file synchronously. Returns the parsed value. Throws on I/O or parse errors with a helpful message.
- readJson(path, options?) reads and parses a JSON file asynchronously. Returns a Promise of the parsed value. Throws on I/O or parse errors with a helpful message.
- isJsonObject(value) type guard for plain JSON object.
- isJsonArray(value) type guard for JSON array.
Options
- baseDir changes the base directory to resolve the path. Defaults to process.cwd().
- encoding sets the file encoding. Defaults to utf8.
Node 18 or newer.
npm install
npm run build
npm test