Skip to content

Commit

Permalink
Add JSON type schema
Browse files Browse the repository at this point in the history
Adds documentation for a JSON type schema as discussed in fabian-hiller#933
  • Loading branch information
jhnns authored Nov 21, 2024
1 parent 64359a3 commit 37bb743
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions website/src/routes/guides/(schemas)/other/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ description: >-
`instance`, `custom` and `lazy` that are not covered in the other guides.
contributors:
- fabian-hiller
- jhnns
---

import { Link } from '@builder.io/qwik-city';
Expand Down Expand Up @@ -71,3 +72,20 @@ const BinaryTreeSchema: v.GenericSchema<BinaryTree> = v.object({
right: v.nullable(v.lazy(() => BinaryTreeSchema)),
});
```

## JSON type schema

Another practical use case for `lazy` is a schema for all possible `JSON` values. These are all values that can be serialized and deserialized without data loss via `JSON.stringify()` and `JSON.parse()`:

```ts
import * as v from 'valibot';

const JsonPrimitiveSchema = v.union([v.string(), v.number(), v.boolean(), v.null()]);
type JsonPrimitiveData = v.InferOutput<typeof JsonPrimitiveSchema>;

const JsonSchema = v.lazy(
(): v.UnionSchema<any, undefined> =>
v.union([JsonPrimitiveSchema, v.array(JsonSchema), v.record(v.string(), JsonSchema)]),
);
type JsonData = JsonPrimitiveData | { [key: string]: JsonData } | Array<JsonData>;
```

0 comments on commit 37bb743

Please sign in to comment.