Skip to main content

Json

Parse, stringify, validate and deep-clone through JSON, with every operation returning a fallback instead of throwing. Parsing untrusted JSON is the classic case where a try/catch is pure noise, so safeJsonParse takes the fallback as an argument. Cloning through JSON was removed in 4.0 along with its objects counterpart: structuredClone is a global on every supported runtime and keeps Dates, Maps, Sets and cycles intact.

Example

import { isValidJson, safeJsonParse, safeJsonStringify } from '@rtorcato/js-common/json'

// localStorage holds whatever the last version of the app wrote there.
const prefs = safeJsonParse<Prefs>(localStorage.getItem('prefs') ?? '', { theme: 'dark' })

safeJsonParse('{bad json') // null
safeJsonStringify({ self: circularRef }) // null instead of a thrown TypeError
isValidJson('[1,2,3]') // true

Import

import { isValidJson, safeJsonParse, safeJsonStringify } from '@rtorcato/js-common/json'

Exports

NameSummary
isValidJsonChecks if a string is valid JSON.
safeJsonParseSafely parses a JSON string, returning a fallback value if parsing fails.
safeJsonStringifySafely stringifies a value to JSON, returning a fallback value if stringification fails.

See also

  • objects — pick, omit, deepMerge, deepClone
  • fetch — JSON helpers and fetch with a timeout
  • validation — type guards — isString, isNumber, isUrl
  • arrays — chunk, unique, groupBy and other array helpers