parseguard
v1.0.1
Published
A lightweight utility that safely parses JSON without crashing applications. Supports fallback values, error logging, and required field validation.
Downloads
276
Maintainers
Readme
parseguard
A lightweight utility that safely parses JSON without crashing applications. Supports fallback values, error logging, and required field validation.
Installation
npm install parseguardUsage
import parse from "parseguard";
const data = parse('{"name":"Karthik"}');
console.log(data.name); // "Karthik"Fallback
Return a default value when JSON is invalid:
const data = parse("bad json", { fallback: {} });
// {}Error Logging
Log parse errors to the console:
parse("bad json", { logError: true });
// [parseguard] Invalid JSON: Unexpected tokenRequired Field Validation
Ensure certain fields exist in the parsed object:
const data = parse('{"id":1}', {
required: ["id", "email"],
fallback: null,
});
// null — "email" is missingCombined with logging:
const data = parse('{"id":1}', {
required: ["id", "email"],
fallback: { error: true },
logError: true,
});
// [parseguard] Missing required fields: email
// { error: true }Browser localStorage
Safely parse values from localStorage:
import parse from "parseguard";
localStorage.setItem("user", '{"name":"Alice"}');
const user = parse.storage("user");
// { name: "Alice" }
const missing = parse.storage("nonexistent", {});
// {}API
parse(json, options?)
| Param | Type | Default | Description |
| ------- | ------ | ------- | ---------------------------------- |
| json | string | required | JSON string to parse |
| options | object | {} | See options below |
Options
| Option | Type | Default | Description |
| -------- | -------- | ------- | ---------------------------------------- |
| fallback | any | null | Value returned on parse failure |
| logError | boolean | false | Log parse/validation errors to console |
| required | string[] | [] | Required field keys to validate |
parse.storage(key, fallback?)
Safely parse a JSON value from localStorage.
Test
node test.jsLicense
MIT
