Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isJSON

Checks if a string is a valid JSON.

TypeScript
Copied!
1/**
2 * Checks if a string is a valid JSON.
3 *
4 * @param str - The string to check.
5 * @returns True if the string is valid JSON, false otherwise.
6 */
7export function isJSON(str: string): boolean {
8  if (typeof str !== 'string') return false;
9  try {
10    const result = JSON.parse(str);
11    return typeof result === 'object' && result !== null;
12  } catch {
13    return false;
14  }
15}
  • Safe Parsing with Error Handling

    Wraps JSON.parse in a try/catch block to gracefully handle malformed input without crashing the application.

  • Object-Only Verification

    Ensures that the parsed result is a non-null object, avoiding cases where JSON.parse("123") would misleadingly return true.

  • Input Type Guard

    Quickly returns false for non-string inputs, avoiding unnecessary processing or runtime errors.

  • Lightweight Utility

    Offers a compact and dependency-free solution for JSON validation, suitable for both frontend and backend contexts.

Tests | Examples

TypeScript
Copied!
1test('returns true for valid JSON objects', () => {
2  expect(isJSON('{"key":"value"}')).toBe(true);
3  expect(isJSON('{"a":1,"b":[1,2,3],"c":null}')).toBe(true);
4});
5
6test('returns true for valid JSON arrays', () => {
7  expect(isJSON('[1, 2, 3]')).toBe(true);
8  expect(isJSON('[]')).toBe(true);
9});
10
11test('returns false for primitives', () => {
12  expect(isJSON('"string"')).toBe(false);
13  expect(isJSON('123')).toBe(false);
14  expect(isJSON('true')).toBe(false);
15  expect(isJSON('null')).toBe(false);
16});
17
18test('returns false for malformed JSON', () => {
19  expect(isJSON('{key:value}')).toBe(false);
20  expect(isJSON('{')).toBe(false);
21  expect(isJSON('')).toBe(false);
22});
23
24test('returns false for non-string inputs', () => {
25  expect(isJSON(undefined as any)).toBe(false);
26  expect(isJSON(null as any)).toBe(false);
27  expect(isJSON(123 as any)).toBe(false);
28});

Common Use Cases

  • Validating API Payloads

    Check if incoming strings (e.g., from HTTP request bodies or query params) are valid JSON before parsing.

  • Form or User Input Validation

    Safely confirm that a string input is valid JSON before applying business logic.

  • Preprocessing Config Files or Templates

    Detect whether configuration files or dynamic text blocks are properly formatted JSON.

  • Data Import or ETL Pipelines

    Filter or reject invalid records before further processing during import/export tasks.

  • Storage Safety Checks

    Ensure that a string being stored to or retrieved from localStorage/sessionStorage is valid JSON.

Codebase: Utilities -> Validation -> isJSON | Yevhen Klymentiev