or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-json-formatter-js

JSON Formatter core library that renders JSON objects in HTML with collapsible navigation functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/json-formatter-js@2.5.x

To install, run

npx @tessl/cli install tessl/npm-json-formatter-js@2.5.0

index.mddocs/

JSON Formatter JS

A TypeScript library for rendering JSON objects in HTML with collapsible navigation, theming support, and interactive features like hover previews and expandable/collapsible tree structures.

Package Information

  • Package Name: json-formatter-js
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install json-formatter-js

Core Imports

import JSONFormatter from "json-formatter-js";

For CommonJS:

const JSONFormatter = require("json-formatter-js");

Individual helper functions (if needed):

import { getType, isObject, getObjectName, getValuePreview, getPreview, cssClass, createElement } from "json-formatter-js";

Basic Usage

import JSONFormatter from "json-formatter-js";

const jsonData = { name: "Alice", age: 30, hobbies: ["reading", "coding"] };
const formatter = new JSONFormatter(jsonData, 2);
document.body.appendChild(formatter.render());

Architecture

JSON Formatter JS follows a class-based architecture where the main JSONFormatter class handles rendering JSON data as interactive HTML elements. It supports nested objects/arrays, customizable themes, animations, and various configuration options for controlling display behavior.

Capabilities

JSON Rendering

Core functionality for converting JSON data into interactive HTML elements with collapsible navigation.

/**
 * Main class for rendering JSON objects in HTML with collapsible navigation
 */
class JSONFormatter {
  /**
   * Creates a new JSONFormatter instance
   * @param json - The JSON object/array to render (not a raw JSON string)
   * @param open - Number of levels to expand initially (default: 1, use Infinity for fully expanded)
   * @param config - Configuration options for appearance and behavior
   * @param key - Internal parameter for nested rendering
   * @param displayKey - Internal parameter for display formatting
   * @param path - Internal parameter for path tracking
   * @param arrayRange - Internal parameter for array chunking
   */
  constructor(
    json: any,
    open?: number,
    config?: JSONFormatterConfiguration,
    key?: string,
    displayKey?: string,
    path?: string[],
    arrayRange?: [number, number]
  );

  /**
   * Renders the JSON formatter as an HTML element
   * @returns HTMLDivElement containing the formatted JSON display
   */
  render(): HTMLDivElement;

  /**
   * Toggles the open/closed state of the formatter
   */
  toggleOpen(): void;

  /**
   * Opens the formatter to a specific depth level
   * @param depth - Number of levels to expand (default: 1, use 0 to collapse all, Infinity to expand all)
   */
  openAtDepth(depth?: number): void;

  /**
   * Generates inline preview text for hover functionality
   * @returns String representation for hover preview
   */
  getInlinepreview(): string;
}

Configuration Options

Comprehensive configuration system for customizing appearance, behavior, and interaction patterns.

interface JSONFormatterConfiguration {
  /**
   * Enable hover preview functionality
   * @default false
   */
  hoverPreviewEnabled?: boolean;

  /**
   * Maximum number of array items to show in hover preview
   * Arrays larger than this show "Array[XXX]" format
   * @default 100
   */
  hoverPreviewArrayCount?: number;

  /**
   * Maximum number of object properties to show in hover preview
   * Objects with more properties get truncated with "..."
   * @default 5
   */
  hoverPreviewFieldCount?: number;

  /**
   * Enable animation when expanding JSON objects
   * @default true
   */
  animateOpen?: boolean;

  /**
   * Enable animation when collapsing JSON objects
   * @default true
   */
  animateClose?: boolean;

  /**
   * Theme name for styling (e.g., 'dark')
   * @default null
   */
  theme?: string;

  /**
   * Use toJSON() method for object serialization when available
   * Useful for Date objects, MongoDB ObjectIDs, etc.
   * @default true
   */
  useToJSON?: boolean;

  /**
   * Custom sorting function for object properties
   * @default null
   */
  sortPropertiesBy?: (a: string, b: string) => number;

  /**
   * Maximum items per array chunk (splits large arrays into groups)
   * @default 100
   */
  maxArrayItems?: number;

  /**
   * Add path data to DOM elements for correlating nodes to original JSON
   * @default false
   */
  exposePath?: boolean;
}

Advanced Usage Patterns

Complex configuration and dynamic control examples for sophisticated use cases.

// Theme configuration
const darkThemeConfig: JSONFormatterConfiguration = {
  theme: 'dark',
  hoverPreviewEnabled: true,
  animateOpen: true,
  animateClose: true
};

// Performance optimized for large datasets
const performanceConfig: JSONFormatterConfiguration = {
  maxArrayItems: 50,
  hoverPreviewArrayCount: 20,
  hoverPreviewFieldCount: 3,
  animateOpen: false,
  animateClose: false
};

// Custom property sorting
const sortedConfig: JSONFormatterConfiguration = {
  sortPropertiesBy: (a: string, b: string) => a.localeCompare(b)
};

// Dynamic control example
const formatter = new JSONFormatter(data, 1, darkThemeConfig);
const element = formatter.render();
document.body.appendChild(element);

// Programmatic expansion control
formatter.openAtDepth(0);        // Collapse all
formatter.openAtDepth(Infinity); // Expand all
formatter.toggleOpen();          // Toggle current state

Data Type Handling

Specialized rendering for different data types with automatic detection and formatting.

// Supported data types with special handling:

// Date objects and date strings - automatically detected and styled
const dateData = {
  created: new Date(),
  modified: "2023-12-05T18:58:53.727Z",
  legacy: "12/05/2023 6:58:53 PM"
};

// URL strings - automatically converted to clickable links
const urlData = {
  homepage: "https://example.com",
  api: "https://api.example.com/v1"
};

// Functions - display signature with collapsed body
const functionData = {
  handler: function processData(input, options) {
    return input.map(item => transform(item, options));
  }
};

// Large arrays - automatically chunked for performance
const largeArrayData = {
  items: new Array(500).fill(0).map((_, i) => ({ id: i, value: i * 2 }))
};

// Objects with toJSON - uses custom serialization
const customData = {
  timestamp: new Date(), // Uses Date.prototype.toJSON()
  // MongoDB ObjectId would also use toJSON()
};

Error Handling and Edge Cases

Built-in handling for common edge cases and error conditions.

// Safe handling of various edge cases:

// Null and undefined values
const edgeCaseData = {
  nullValue: null,
  undefinedValue: undefined,
  emptyObject: {},
  emptyArray: [],
  emptyString: ""
};

// Objects without constructors
const objectWithoutConstructor = Object.create(null);
objectWithoutConstructor.data = "value";

// Circular references - handled via toJSON when useToJSON is true
const circularRef = { a: 1 };
circularRef.self = circularRef; // Only safe if object has toJSON method

// Functions with malformed signatures - gracefully handled
const malformedFunction = new Function("return 42");

// Very deep nesting
const deepObject = { level1: { level2: { level3: { level4: { value: "deep" } } } } };

// All these cases are handled gracefully by JSONFormatter
const formatter = new JSONFormatter(edgeCaseData);

Helper Functions

Utility functions exported by the library for advanced use cases and custom implementations.

/**
 * Gets the type of a value, returning "null" for null objects
 * @param value - Any value to check type for
 * @returns Type string (JavaScript primitive types plus "array" and "null")
 */
function getType(value: any): string;

/**
 * Determines if a value is an object (including arrays)
 * @param value - Value to check
 * @returns True if value is an object type
 */
function isObject(value: any): boolean;

/**
 * Gets constructor name of an object
 * @param object - Object to get constructor name from
 * @returns Constructor name string
 */
function getObjectName(object: Object): string;

/**
 * Generates inline preview for a JavaScript object based on type and value
 * @param type - Type string from getType()
 * @param object - Original object for reference
 * @param value - String representation of the value
 * @returns Formatted preview string
 */
function getValuePreview(type: string, object: Object, value: string): string;

/**
 * Generates inline preview for any JavaScript object
 * @param object - Object to generate preview for
 * @returns Preview string representation
 */
function getPreview(object: any): string;

/**
 * Generates a prefixed CSS class name for styling
 * @param className - Base class name
 * @returns Prefixed class name (json-formatter-{className})
 */
function cssClass(className: string): string;

/**
 * Creates a new DOM element with given type and class
 * @param type - HTML element type (e.g., 'div', 'span')
 * @param className - Optional CSS class name (gets prefixed)
 * @param content - Optional content (Element or string)
 * @returns Created DOM Element
 */
function createElement(
  type: string,
  className?: string,
  content?: Element | string
): Element;

Usage Examples:

import { getType, isObject, getPreview, cssClass, createElement } from "json-formatter-js";

// Type checking
const valueType = getType({ foo: "bar" }); // "object"
const isObj = isObject([]); // true (arrays are objects)

// Preview generation
const preview = getPreview([1, 2, 3]); // "Array[3]"

// CSS class generation
const className = cssClass("value"); // "json-formatter-value"

// DOM element creation
const element = createElement("div", "container", "Hello World");
// Creates: <div class="json-formatter-container">Hello World</div>

Types

/**
 * Configuration interface for JSONFormatter behavior and appearance
 */
interface JSONFormatterConfiguration {
  hoverPreviewEnabled?: boolean;
  hoverPreviewArrayCount?: number;
  hoverPreviewFieldCount?: number;
  animateOpen?: boolean;
  animateClose?: boolean;
  theme?: string;
  useToJSON?: boolean;
  sortPropertiesBy?: (a: string, b: string) => number;
  maxArrayItems?: number;
  exposePath?: boolean;
}

/**
 * Default configuration values
 */
const defaultConfig: JSONFormatterConfiguration = {
  hoverPreviewEnabled: false,
  hoverPreviewArrayCount: 100,
  hoverPreviewFieldCount: 5,
  animateOpen: true,
  animateClose: true,
  theme: null,
  useToJSON: true,
  sortPropertiesBy: null,
  maxArrayItems: 100,
  exposePath: false
};