Skip to content

parseJson

type: function

The parseJson function wraps JSON.parse and returns undefined when parsing fails.

Usage

import { parseJson } from '@mustib/utils';
type User = { name: string; email: string };
const user = parseJson<User>('{"name":"A","email":"a@mail.com"}');
const invalid = parseJson<User>('not-json');
console.log(user?.name); // A
console.log(invalid); // undefined

Definition

function parseJson<T>(value: string): T | undefined { }

Parameters

  1. value
    type value = string;
    • JSON string to parse.

Returns

type T = T | undefined;
  • Parsed value when valid JSON is provided.
  • `undefined` when parsing fails.