Skip to content

safeParseSequence

Parses a JSON text sequence (RFC 7464) like parseSequence, but returns null (or fallback) instead of throwing on invalid input.

Accepts / rejects: exactly what parseSequence does, with the same ParseSequenceOptions.

On invalid input: returns fallback when one is given — even undefined, which is told apart from an omitted argument — and null otherwise. Never throws. To pass options without a fallback, pass null as the fallback.

Available since v3.1.3

import { safeParseSequence } from '@helpers4/json';
// or, from the all-in-one package (same code, one install):
import { safeParseSequence } from 'helpers4/json';
safeParseSequence<T = unknown>(text: string): T[] | null
ParameterTypeDescription
textstringThe JSON text sequence

T[] | null — The parsed values typed as T[], or null on invalid input (pass a fallback to get it instead)

Returns null if any record is invalid.

safeParseSequence('\u001E1\n') // => [1]
safeParseSequence('\u001E{\n') // => null

The fallback is returned on invalid input.

safeParseSequence('\u001E{\n', [])
// => []

Options for parseSequence and safeParseSequence.

interface ParseSequenceOptions {
  invalidRecords?: "skip" | "fail";
}

View source on GitHub