Hyperlinkv0.8.0-beta.28

Formatter

Formatter.formatJsonfunctioneffect/Formatter.ts:297
(
  input: unknown,
  options?: { readonly space?: number | string | undefined }
): string

Stringifies a value to JSON safely, silently dropping circular references.

When to use

Use when you need valid JSON output, unlike format, and the input may contain circular references that should be silently omitted rather than throwing a TypeError.

Details

Uses JSON.stringify internally with a replacer that tracks the current object ancestry. Circular references are replaced with undefined, which omits them from object output. Redactable values are automatically redacted before serialization. Values not supported by JSON, such as BigInt, Symbol, undefined, and functions, follow standard JSON.stringify behavior. The space parameter controls indentation and defaults to 0.

Example (Formatting compact JSON)

import { Formatter } from "effect"

console.log(Formatter.formatJson({ name: "Alice", age: 30 }))
// {"name":"Alice","age":30}

Example (Handling circular references)

import { Formatter } from "effect"

const obj: any = { name: "test" }
obj.self = obj
console.log(Formatter.formatJson(obj))
// {"name":"test"}

Example (Pretty-printed JSON)

import { Formatter } from "effect"

console.log(Formatter.formatJson({ name: "Alice", age: 30 }, { space: 2 }))
// {
//   "name": "Alice",
//   "age": 30
// }
serializationformatFormatter
export function formatJson(input: unknown, options?: {
  readonly space?: number | string | undefined
}): string {
  const ancestors: Array<object> = []
  return JSON.stringify(
    input,
    function(this: unknown, _key: string, value: unknown) {
      const redacted = redact(value)
      if (typeof redacted !== "object" || redacted === null) {
        return redacted
      }
      while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {
        ancestors.pop()
      }
      if (ancestors.includes(redacted)) {
        return undefined // circular reference
      }
      ancestors.push(redacted)
      return redacted
    },
    options?.space
  )
}
Referenced by 2 symbols