seitu
Version:
23 lines (22 loc) • 454 B
JavaScript
//#region src/utils/json/index.ts
/**
* Parses JSON; returns the input when it is not a string or is invalid JSON.
*
* @example
* ```ts twoslash
* import { tryParseJson } from 'seitu/utils'
*
* tryParseJson('{"a":1}') // { a: 1 }
* tryParseJson('oops') // 'oops'
* ```
*/
function tryParseJson(value) {
if (typeof value !== "string") return value;
try {
return JSON.parse(value);
} catch {
return value;
}
}
//#endregion
export { tryParseJson };