DEV Community

scl
scl

Posted on

JSON schema parser

Been thinking about a model validation/parsing issue lately.

Background

I use JSON schema in AWS API gateway to validate the incoming event payload. If the payload gets to reach my Lambda codes downstream, those Lambda codes parse the payload into a strongly typed object using Zod.

Problem statement

How then can we prevent manual duplication and have a single source of JSON schema for API gateway (for validation) and our Lambda codes (for parsing into strongly typed objects)?

Zod doesn't really interoperate with JSON schema without some third party adapters. Hence that sent me on a search for a parser that plays well with JSON schema.

Probable solution

That search led me to a promising candidate that's used by some 30 million people:
https://ajv.js.org/guide/typescript.html#utility-type-for-jtd-data-type

Top comments (1)

Collapse
 
albertwei profile image
Albert

This is a useful problem space. The part about avoiding two definitions for JSON Schema and Zod is especially relatable.

When you convert JSON Schema to Zod, how do you usually handle edge cases like anyOf, nullable fields, or custom formats? Those always seem to be where the simple examples stop being simple.