Created
July 20, 2022 18:54
-
-
Save itsMapleLeaf/c89fc5b2a1bbff580552450e73c02112 to your computer and use it in GitHub Desktop.
sanitize json function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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