Home > widget-integration > FilterHelper > safeParseJSON

FilterHelper.safeParseJSON() method

Safely parses JSON string with optional type guard validation.

Provides safe JSON parsing that catches exceptions and returns null on failure. Supports optional type guard function for runtime type validation. This is essential for parsing user-provided data, metadata attributes, and API responses. Override this method to add logging, custom error handling, or preprocessing of JSON strings.

Signature:

safeParseJSON(json: string): unknown | null;

Parameters

Parameter

Type

Description

json

string

JSON string to parse

Returns:

unknown | null

Parsed object if successful and passes guard (if provided), null otherwise

Example 1

Basic usage without guard:

const data = this.filterHelper.safeParseJSON('{"key": "value"}');
// Returns: { key: "value" } or null if invalid

Example 2

With type guard:

interface Product { id: string; name: string; }
const isProduct = (obj: unknown): obj is Product =>
  typeof obj === 'object' && obj !== null && 'id' in obj && 'name' in obj;

const product = this.filterHelper.safeParseJSON<Product>(
  productJson,
  isProduct
);

Example 3

Extend to add parsing analytics:

window.boostWidgetIntegration.extend('FilterHelper', (FilterHelper) => {
  return class CustomFilterHelper extends FilterHelper {
    safeParseJSON(json, guard) {
      const result = super.safeParseJSON(json, guard);
      if (result === null) {
        // Track parsing failures for debugging
        analytics.track('json_parse_error', { json: json.substring(0, 100) });
      }
      return result;
    }
  };
});