How to create a type from json or jsonschema?

Thanks for this great library first! If a type can be serialized to an arktype schema by .toJSON (or a json schema by .toJsonSchema), how can I re-create that type with the json data? Another question, how can I check if an arktype schema extends another arktype schema? Thanks!
4 Replies
TizzySaurus
TizzySaurus22h ago
JSON Schema to ArkType is something I've actually got a PR up for that'll hopefully be merged soon™️. https://github.com/arktypeio/arktype/pull/1159 There is rootSchema from @ark/schema, which converts the ArkType internal schema (from type.toJSON() ig?) (the thing that looks like {domain: "number"} for type("number")) into an actual ArkType type. It obviously won't work for non-json-serialisable types like things with morphs etc. though
GitHub
feat: support JSON Schema as input for a Type by TizzySaurus · Pul...
Closes #729. What This PR adds @ark/jsonschema, which is a library enabling users to convert a valid JSON Schema schema into an ArkType type. API Below is a basic sample-use of @ark/jsonschema: imp...
TizzySaurus
TizzySaurus22h ago
I believe type.json is what gives the internal schema I'm referring to. Not sure if that's the same as type.toJSON() (can't remember what that does, and I don't see it in the docs)
freeyourmind
freeyourmindOP22h ago
import { type } from "arktype"; import { schemaScope, rootSchema } from "@arktype/schema"; const bounded = type({ nonEmpty: "string > 0", atLeastLength3: "string.alphanumeric >= 3", lessThanLength10: "string < 10", atMostLength5: "string <= 5", }); const bounded2 = rootSchema(bounded.json as any); const types = schemaScope({ bounded: bounded.json as any, }).export(); const bounded3 = types.bounded; console.log(bounded2.extends(bounded)); // true console.log(bounded.extends(bounded2)); // true console.log(bounded3.extends(bounded)); // true console.log(bounded.extends(bounded3)); // true It works! Thanks!
ssalbdivad
ssalbdivad11h ago
Keep in mind this will not work yet if it includes non-serializable conditions like custom functions

Did you find this page helpful?