Skip to content

rish405/safe-json-parse-lite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

safe-json-parse-lite

Tiny, zero-dependency, TypeScript-first helper for safe JSON.parse with conservative repairs. ESM + CJS dual outputs and automatic .d.ts.

Install

npm i safe-json-parse-lite

Usage

ESM:

import safeJsonParse, { safeJsonParse as parse, parseOr } from 'safe-json-parse-lite';

const a = parse<{ a: number }>('{"a":1}');
if (a.ok) {
  console.log(a.value.a); // 1
}

const b = parseOr('{"a":1,}', { a: 0 }); // repairs trailing comma
// { a: 1 }

CJS:

const { default: safeJsonParse, safeJsonParse: parse, parseOr } = require('safe-json-parse-lite');
const res = safeJsonParse("{'a':1}"); // converts simple single quotes

API

  • safeJsonParse<T>(input: string): { ok: true, value: T } | { ok: false, error: unknown }

    • Tries JSON.parse. On failure, applies repairs and tries again. If still failing, returns the first error.
  • parseOr<T>(input: string, fallback: T): T

    • Returns parsed value or the provided fallback.
  • default export is safeJsonParse.

Repairs

  • Trim leading/trailing whitespace.
  • Remove BOM (\uFEFF) at the start.
  • Remove trailing commas before } or ].
  • If there are single quotes and no double quotes, convert simple '...' to "...".

Safety Notes

  • This is not a full JSON sanitizer. Repairs are intentionally minimal.
  • Single-quote conversion is conservative and may not handle all edge cases; avoid relying on it for complex strings containing apostrophes.
  • Always validate untrusted inputs upstream when possible.

Motivation

Parsing external JSON can fail for minor formatting issues (BOM, trailing commas, single quotes). This library provides a tiny, dependency-free helper to make parsing resilient without pulling heavy parsers.

Build and Test

npm run build
npm test

Publish

npm login
npm publish
  • For scoped packages use npm publish --access public.
  • Update the repository.url in package.json before publishing.

Bump Version

npm version patch   # 1.0.1
npm version minor   # 1.1.0
npm version major   # 2.0.0

Push tags if using Git:

git push --follow-tags

Optional CI (GitHub Actions)

Create .github/workflows/publish.yml:

name: Publish on tag

on:
  push:
    tags:
      - "v*"

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
          registry-url: https://registry.npmjs.org
      - run: npm ci
      - run: npm run build
      - run: npm test
      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published