@squiz/json-schema-library
Version:
Customizable and hackable json-validator and json-schema utilities for traversal, data generation and validation
27 lines (22 loc) • 735 B
text/typescript
import getTypeOf from "./getTypeOf";
import { JSONSchema } from "./types";
/**
* Create a simple json schema for the given input data
* @param data - data to get json schema for
* @return schema
*/
export default function createSchemaOf(data: any): JSONSchema {
const schema: JSONSchema = {
type: getTypeOf(data)
};
if (schema.type === "object") {
schema.properties = {};
Object.keys(data).forEach((key) => (schema.properties[key] = createSchemaOf(data[key])));
}
if (schema.type === "array" && data.length === 1) {
schema.items = createSchemaOf(data[0]);
} else if (schema.type === "array") {
schema.items = data.map(createSchemaOf);
}
return schema;
}