Created
October 12, 2024 23:37
-
-
Save yvbbrjdr/b7b7acec252aa95ca93894b316dc2ae3 to your computer and use it in GitHub Desktop.
Extract schema
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 SchemaType = | |
| string | |
| { [key: string]: SchemaType } | |
| [string, SchemaType | null]; | |
function extractSchema(obj: any): SchemaType { | |
if (obj === null) { | |
return "null"; | |
} | |
if (typeof obj === "object") { | |
if (Array.isArray(obj)) { | |
return [ | |
`array[${obj.length}]`, | |
obj.length > 0 ? extractSchema(obj[0]) : null, | |
]; | |
} else { | |
const result: { [key: string]: SchemaType } = {}; | |
for (const [key, value] of Object.entries(obj)) { | |
result[key] = extractSchema(value); | |
} | |
return result; | |
} | |
} | |
return typeof obj; | |
} |
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
def extract_schema(obj): | |
if isinstance(obj, dict): | |
return {k: extract_schema(v) for k, v in obj.items()} | |
if isinstance(obj, list): | |
return [f'list[{len(obj)}]', extract_schema(obj[0]) if obj else None] | |
return type(obj).__name__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment