Hyperlinkv0.8.0-beta.28

Inspectable

Inspectable.toJsonconsteffect/Inspectable.ts:152
(input: unknown): unknown

Converts a value to a JSON-serializable representation safely.

When to use

Use when you need a safe, JSON-serializable representation of a value without risking unhandled errors.

Details

This function attempts to extract JSON data from objects that implement the toJSON method, recursively processes arrays, and handles errors gracefully. For objects that don't have a toJSON method, it applies redaction to protect sensitive information.

convertingtoStringUnknown
export const toJson = (input: unknown): unknown => {
  try {
    if (
      Predicate.hasProperty(input, "toJSON") &&
      Predicate.isFunction(input["toJSON"]) &&
      input["toJSON"].length === 0
    ) {
      return input.toJSON()
    } else if (Array.isArray(input)) {
      return input.map(toJson)
    }
  } catch {
    return "[toJSON threw]"
  }
  return redact(input)
}
Referenced by 2 symbols