Proposal: built-in JSON Schema validation

It’s common today to perform schema validation on incoming JSON from an HTTP response, e.g. with tools like ZOD (GitHub - colinhacks/zod: TypeScript-first schema validation with static type inference).

What if the web platform provided this in a standard, performant and non-blocking way? It would make it much easier to avoid a very common type of bugs without blocking the main thread, creating new service-worker code, or having to choose between all kinds of schema validation libs.

Strawman API:

const response = await fetch("...");
const data = await response.json({schema: "my-json-schema.json"});

How would you imagine error catching would look for such API?

Perhaps somehing like this:

const response = await fetch("...");
let data = null;
try {
  data = await response.json({schema: "my-json-schema.json"});
} catch (error) {
  if (error instanceof SyntaxError) {
    alert("This ain't JSON": + error.message);
  } else if (error instanceof TypeError) {
    alert("This is JSON but schema validation failed": + error.message);

(instanceof for demonstration purposes that it’s different error types)

btw I think that once we have async JSON parsing we can add schema validation there as well.