A lightweight utility that safely parses JSON without crashing applications. Supports fallback values, error logging, and required field validation.
npm install parseguardimport parse from "parseguard";
const data = parse('{"name":"Karthik"}');
console.log(data.name); // "Karthik"Return a default value when JSON is invalid:
const data = parse("bad json", { fallback: {} });
// {}Log parse errors to the console:
parse("bad json", { logError: true });
// [parseguard] Invalid JSON: Unexpected tokenEnsure 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 }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", {});
// {}| Param | Type | Default | Description |
|---|---|---|---|
| json | string | required | JSON string to parse |
| options | object | {} |
See options below |
| 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 |
Safely parse a JSON value from localStorage.
node test.jsMIT