Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Langfuse Langfuse JSON Utils

From Leeroopedia
Knowledge Sources
Domains Utilities, JSON, Parsing
Last Updated 2026-02-14 00:00 GMT

Overview

This module provides JSON parsing utilities including deep recursive parsing of nested stringified JSON, Python dict-to-JSON conversion, an iterative high-performance parser, and a precision-preserving JSON parser for large numbers.

Description

The json.ts utility module contains three primary exported functions and several internal helpers that handle common JSON parsing challenges encountered in the Langfuse platform:

deepParseJson - Recursively parses JSON strings that may contain nested stringified JSON (a common pattern when LLM frameworks serialize data). It accepts configurable maxSize (default 500KB) and maxDepth (default 3) options to prevent UI freezing on large payloads. Strings that parse to numbers are intentionally kept as strings to preserve the original representation. It also includes prototype pollution protection by filtering out __proto__, constructor, and prototype keys.

deepParseJsonIterative - An alternative high-performance iterative implementation of the same deep parsing logic. It uses a stack-based approach with ParseStackEntry objects to avoid call stack limitations on deeply nested data. The implementation uses bottom-up reconstruction, only creating new objects when child values actually changed, and maintains semantic equivalence with the recursive version.

parseJsonPrioritised - A JSON parser that preserves precision for large numbers. It uses a two-path strategy:

  • Fast path: Uses native JSON.parse when no potentially unsafe numbers are detected (checked via regex for 13+ digit sequences or scientific notation).
  • Slow path: Uses the lossless-json library to parse, converting safe numbers to native Number and preserving large integers beyond safe limits as strings.

tryParsePythonDict (internal) - Attempts to convert Python dict/list string literals to valid JSON by replacing True/False/None with their JSON equivalents and converting single quotes to double quotes. This handles the common case where LangChain/LangGraph v1 tool calls are logged as Python dicts. It includes performance guards: early termination if no single quotes or structure characters are present, and a 1MB size limit.

Usage

Use these functions when you need to:

  • Display deeply nested JSON data in the Langfuse UI that may contain stringified JSON at multiple levels.
  • Parse JSON from LLM tool call outputs that may be Python dict format instead of standard JSON.
  • Parse JSON containing large integer IDs or token counts that would lose precision with native JSON.parse.
  • Process potentially large JSON payloads without freezing the UI or blowing the call stack.

Code Reference

Source Location

Signature

export interface DeepParseJsonOptions {
  /** Maximum size in bytes before skipping parsing (default: 500KB) */
  maxSize?: number;
  /** Maximum recursion depth (default: 3) */
  maxDepth?: number;
}

export function deepParseJson(
  json: unknown,
  options?: DeepParseJsonOptions,
): unknown;

export function deepParseJsonIterative(
  json: unknown,
  options?: DeepParseJsonOptions,
): unknown;

export const parseJsonPrioritised: (
  json: string,
) => JsonNested | string | undefined;

Import

import {
  deepParseJson,
  deepParseJsonIterative,
  parseJsonPrioritised,
} from "@langfuse/shared/src/utils/json";

I/O Contract

Inputs

Name Type Required Description
json (deepParseJson) unknown Yes A JSON string, object, array, or primitive that may contain nested stringified JSON
options.maxSize number No Maximum JSON string size in bytes before skipping parsing (default: 500,000)
options.maxDepth number No Maximum recursion depth for nested parsing (default: 3)
json (parseJsonPrioritised) string Yes A JSON string that may contain large numbers requiring precision preservation

Outputs

Name Type Description
deepParseJson result unknown The deeply parsed JSON with all nested stringified JSON resolved up to maxDepth; strings that are numbers remain as strings
deepParseJsonIterative result unknown Same as deepParseJson but computed iteratively for stack safety
parseJsonPrioritised result string | undefined Parsed JSON with large integers preserved as strings; returns original string if parsing fails

Usage Examples

import { deepParseJson, deepParseJsonIterative, parseJsonPrioritised } from "@langfuse/shared/src/utils/json";

// Deep parse nested stringified JSON
const input = '{"key": "{\\"nested\\": \\"value\\"}"}';
const result = deepParseJson(input);
// result => { key: { nested: "value" } }

// Parse with custom depth and size limits
const largeInput = { data: '{"inner": "{\\"deep\\": true}"}' };
const parsed = deepParseJson(largeInput, { maxSize: 1_000_000, maxDepth: 5 });

// Parse Python dict format (from LangChain tool calls)
const pythonDict = "{'key': 'value', 'flag': True, 'nothing': None}";
const jsonResult = deepParseJson(pythonDict);
// jsonResult => { key: "value", flag: true, nothing: null }

// Use iterative version for stack-safe parsing of very deep structures
const deepResult = deepParseJsonIterative(someDeepStructure);

// Parse JSON with large numbers preserving precision
const jsonWithBigInt = '{"id": 9007199254740993, "name": "test"}';
const precise = parseJsonPrioritised(jsonWithBigInt);
// precise => { id: "9007199254740993", name: "test" }
// The large integer is preserved as a string to avoid precision loss

// Safe numbers are kept as native numbers
const jsonWithSafeInt = '{"count": 42, "name": "test"}';
const safe = parseJsonPrioritised(jsonWithSafeInt);
// safe => { count: 42, name: "test" }

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment