Tiny, zero-dependency, TypeScript-first helper for safe JSON.parse with conservative repairs. ESM + CJS dual outputs and automatic .d.ts.
npm i safe-json-parse-liteESM:
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-
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.
- Tries
-
parseOr<T>(input: string, fallback: T): T- Returns parsed value or the provided fallback.
-
defaultexport issafeJsonParse.
- 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"...".
- 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.
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.
npm run build
npm testnpm login
npm publish- For scoped packages use
npm publish --access public. - Update the
repository.urlinpackage.jsonbefore publishing.
npm version patch # 1.0.1
npm version minor # 1.1.0
npm version major # 2.0.0Push tags if using Git:
git push --follow-tagsCreate .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 }}