Skip to content

Instantly share code, notes, and snippets.

@yvbbrjdr
Created October 12, 2024 23:37
Show Gist options
  • Save yvbbrjdr/b7b7acec252aa95ca93894b316dc2ae3 to your computer and use it in GitHub Desktop.
Save yvbbrjdr/b7b7acec252aa95ca93894b316dc2ae3 to your computer and use it in GitHub Desktop.
Extract schema
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;
}
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