0.1.2 • Published 4 months ago

@crescendolab/parse-json v0.1.2

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

@crescendolab/parse-json

A user-friendly wrapper for JSON.parse().

// ✅ Returns type `JsonValue` which is stricter than `unknown`.
// ✅ Fallback specified value is returned if `input` is not a valid JSON string.
const output = parseJson(input, null);
//    ^? const output: JsonValue
if (typeof output === "function") {
  output;
  // ^? const output: never
}
if (output === undefined) {
  output;
  // ^? const output: never
}

// ❌ Return with type `any`.
// ❌ Might throw an error if `input` is not a valid JSON string.
const vanillaOutput = JSON.parse(input);
//    ^? const vanillaOutput: any

Installation

pnpm i @crescendolab/parse-json

Usage

import { parseJson } from "@crescendolab/parse-json";

const input = await loadJson();
const output = parseJson(input);

Options

parseJson(input, options);

options.fallback

  • Type: any

Specify a fallback value to be returned if it fails to parse input as a JSON string.

const input = "not a valid json string";

// ✅ Get `undefined` instead of throwing an error.
const output = parseJson(input, { fallback: undefined });

options.parser

  • Type: (input: string) => JsonValue

Specify a custom parser function.

For example, you can use json5 for comments in json or parse-json for helpful error messages.

import { parseJson } from "@crescendolab/parse-json";
import json5 from "json5";

const input = `{
  // This is a comment
  "foo": "bar"
}`;

// ✅ This will not throw an error.
const output = parseJson(input, {
  parser: json5.parse,
});

Create your own parser

You can create a parser with a custom default options where the options are the same as the options argument of parseJson().

import { parseJson } from "@crescendolab/parse-json";

const myParser = parseJson.create(options);
const myParser = parseJson.create({ fallback: undefined });

License

MIT © Crescendo lab

0.1.2

4 months ago

0.1.1

1 year ago

0.1.0

1 year ago