Skip to content

Gsaudx/ts-simple-json-reader

Repository files navigation

ts-simple-json-reader

A tiny, zero-dependency TypeScript utility to read JSON files safely.

Install

npm install ts-simple-json-reader

Usage (library)

import { 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();

Usage (CLI)

npx ts-simple-json-reader ./data/sample.json

API

  • 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 support

Node 18 or newer.

Development

npm install
npm run build
npm test

About

A simple TypeScript CLI that reads a JSON and prints statistics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors