fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
6.32k stars 203 forks source link

JSON type #933

Open jhnns opened 3 days ago

jhnns commented 3 days ago

Hello, thanks for this great library 👋

I was wondering if you'd be interested in a documentation for a JSON serializable type. That's the type that you can safely serialize and de-serialize via JSON.parse(JSON.stringify(thing)). Zod mentions it in their documentation.

My suggestion (based on Zod's implementation) would be:

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

type Json = JsonLiteral | { [key: string]: Json } | Array<Json>;
const Json = v.lazy(
  (): v.UnionSchema<any, undefined> =>
    v.union([JsonLiteral, v.array(Json), v.record(v.string(), Json)]),
);

Maybe this could even be included in valibot so that people don't need to copy it.

fabian-hiller commented 1 day ago

Where would you place to code in the docs?

Here is a JSON schema I wrote a few months ago:

type Json = string | number | boolean | null | { [key: string]: Json } | Json[];
type LiteralIssue = StringIssue | NumberIssue | BooleanIssue | NullIssue;
type JsonIssue = LiteralIssue | ArrayIssue | RecordIssue;
type JsonSchema = BaseSchema<Json, Json, UnionIssue<JsonIssue> | JsonIssue>;
export const jsonSchema = v.lazy(() =>
    v.union([v.string(), v.number(), v.boolean(), v.null_(), v.array(jsonSchema), v.record(v.string(), jsonSchema)])
) as JsonSchema;
jhnns commented 1 day ago

I think I'd expect it under Guides > Advanced. What do you think about implementing it as valibot action?

fabian-hiller commented 23 hours ago

We could at it to https://valibot.dev/guides/other/. Feel free to create a PR.

I see and DX advantage of adding a json schema. But I have to think about it because it is a very special kind of schema compared to our other schemas that just mimic TS type functionality. Also, we have had ideas in the past to add something like a json action to validate JSON strings. We need to make sure the naming makes sense. I think this is something I would prefer to investigate after our v1 release.

jhnns commented 3 hours ago

I've created a PR. valibot.dev/guides/other is the perfect spot, right below lazy :)

I understand that shipping a json schema is a special case that you might want to think about. I think it would be nice 😁