Skip to content

safeParseLines

Parses newline-delimited JSON (NDJSON, JSON Lines) like parseLines, but returns null (or fallback) instead of throwing on invalid input.

Accepts / rejects: exactly what parseLines does, with the same ParseLinesOptions.

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

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

Returns null if any line is invalid.

safeParseLines('1\n2\n') // => [1, 2]
safeParseLines('1\n{')   // => null

Pass null as the fallback to give options.

safeParseLines('1\n\n2', null, { blankLines: 'fail' })
// => null (JSON Lines forbids blank lines)

Options for parseLines and safeParseLines.

interface ParseLinesOptions {
  blankLines?: "skip" | "fail";
  invalidLines?: "skip" | "fail";
}

View source on GitHub