safe-text-to-json
v1.0.0
Published
Extracts and parses the first JSON object inside noisy strings without throwing.
Maintainers
Readme
safe-text-to-json
safeJsonParse extracts the first JSON object that appears inside a noisy string and returns that object, or null
if there is no valid JSON payload. It is meant for toolchains where untrusted data is interleaved with markup, logging
prefixes, or other extraneous content.
Installation
npm install safe-text-to-jsonUsage
import safeJsonParse from "safe-text-to-json";
const raw = "prefix {\"id\": 42} suffix";
const result = safeJsonParse<{ id: number }>(raw);
if (result) {
console.log("parsed id", result.id);
} else {
console.log("no valid JSON found");
}The parser only inspects the first { … } pair, so if a string contains multiple JSON fragments the earliest one is
returned. Any failure or malformed content yields null instead of throwing.
API
safeJsonParse(text)
text: string that may contain a JSON object- Returns the parsed object or
nullon failure
Development
npm install
npm run buildThe TypeScript sources live under src, and the dist folder is generated by tsc --build tsconfig.build.json.
