UNPKG

parse-json-object

Version:
31 lines (30 loc) 861 B
import { isJSONObject, isJSONValue, isJSONArray, isString } from "types-json"; import { validate } from "is-zod"; export function parse(text, validator) { if (text) { try { const json = JSON.parse(text); if (typeof validator === "function") { return validator(json) ? json : undefined; } else { return validate(validator)(json) ? json : undefined; } } catch (err) { return undefined; } } else { return undefined; } } export function parseJSONValue(text) { return parse(text, isJSONValue); } export function parseJSONObject(text) { return parse(text, isJSONObject); } export function parseJSONArray(text) { return parse(text, isJSONArray); } export function parseString(text) { return parse(text, isString); }