Generate a Simple YAML Schema from JSON
Learn how to convert a flat JSON object into a YAML Schema definition that validates structure, types, and required fields. Covers basic property mapping and schema metadata.
Detailed Explanation
From JSON to a Basic YAML Schema
The simplest conversion takes a flat JSON object and produces a YAML Schema that describes its structure. Every key becomes a property entry with a type constraint inferred from the JSON value.
Example JSON Input
{
"name": "my-service",
"version": "1.0.0",
"port": 8080,
"debug": false
}
Generated YAML Schema
type: object
properties:
name:
type: string
version:
type: string
port:
type: integer
debug:
type: boolean
required:
- name
- version
- port
- debug
How Type Inference Works
| JSON value | YAML Schema type |
|---|---|
"hello" |
string |
42 |
integer |
3.14 |
number |
true / false |
boolean |
null |
nullable (no type, or type: "null") |
Schema Metadata
You can enrich the generated schema with metadata fields:
$schema: "http://json-schema.org/draft-07/schema#"
title: ServiceConfig
description: Configuration for a microservice
type: object
properties:
name:
type: string
description: The service identifier
version:
type: string
pattern: "^\\d+\\.\\d+\\.\\d+$"
port:
type: integer
minimum: 1
maximum: 65535
debug:
type: boolean
default: false
Why YAML for Schemas?
YAML schemas are more readable than their JSON equivalents, especially for configuration files that developers edit by hand. The absence of braces and quotes reduces visual clutter, making schema reviews faster during code review. YAML also supports comments, so you can annotate constraints directly in the schema file.
Validating Against the Schema
Tools like ajv, yamale, and pykwalify can validate YAML documents against a YAML schema. In CI/CD pipelines, schema validation catches configuration errors before deployment.
Use Case
When creating a new microservice, you often start with a sample configuration JSON and need to define a schema that validates all future config files. Generating the YAML schema from a known-good JSON gives you an instant starting point that you can refine with additional constraints like min/max values and patterns.