Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created July 20, 2022 18:54
Show Gist options
  • Select an option

  • Save itsMapleLeaf/c89fc5b2a1bbff580552450e73c02112 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/c89fc5b2a1bbff580552450e73c02112 to your computer and use it in GitHub Desktop.
sanitize json function
type JsonValue =
| string
| number
| boolean
| null
| JsonValue[]
| JsonObject
type JsonObject = { [key: string]: JsonValue }
/** Recursively removes values that can't be json serialized */
function sanitizeJson(value: unknown): JsonValue | undefined {
if (
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ||
value === null
) {
return value
}
if (Array.isArray(value)) {
return value.flatMap((v) => {
const sanitized = sanitizeJson(v)
return sanitized === undefined ? [] : [sanitized]
})
}
if (typeof value === "object") {
const result: JsonObject = {}
for (const [k, v] of Object.entries(value)) {
const sanitized = sanitizeJson(v)
if (sanitized !== undefined) {
result[k] = sanitized
}
}
return result
}
return undefined
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment