惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
博客园_首页
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
美团技术团队
小众软件
小众软件
Jina AI
Jina AI
S
SegmentFault 最新的问题
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JSON Schema in Dart
Mathieu Kerjouan · 2026-06-25 · via DEV Community

Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.
-- Friedrich Niezsche

When you know how to encode and decode JSON data, it can become annoying to deal with the structure every time. Worse, it can become a nightmare when some kind of data structure are being upgraded. That why some people created JSON Schema. The idea is to define what kind of fields and values should be contained in JSON objects. A package called json_schema was created to implement this standard.

Bootstrapping

$ dart create validate
Creating validate using template console...

  .gitignore
  analysis_options.yaml
  CHANGELOG.md
  pubspec.yaml
  README.md
  bin/validate.dart
  lib/validate.dart
  test/validate_test.dart

Running pub get...                     0.3s
  Resolving dependencies...
  Downloading packages...
  Changed 48 dependencies!
  3 packages have newer versions incompatible with dependency constraints.
  Try `dart pub outdated` for more information.

Created project validate in validate! In order to get started, run the following commands:

  cd validate
  dart run

$ cd validate

$ dart pub add json_schema
Resolving dependencies... 
Downloading packages... 
  _fe_analyzer_shared 103.0.0 (104.0.0 available)
  analyzer 13.3.0 (14.0.0 available)
+ http 1.6.0
+ json_schema 5.2.2
  package_config 2.2.0 (3.0.0 available)
+ quiver 3.2.2
+ rfc_6901 0.2.1
+ uri 1.0.0
Changed 5 dependencies!
3 packages have newer versions incompatible with dependency constraints.
Try `dart pub outdated` for more information.

We can edit bin/validate.dart and import the json_schema package.

import 'package:json_schema/json_schema.dart';

Schema Conception

Don't trust, just verify.
-- Steven Levitt

For this example, we will use the examples present in the JSON Schema Getting Started tutorial. Their first JSON object looks like that:

{
  "productId": 1,
  "productName": "A green door",
  "price": 12.50,
  "tags": [
    "home",
    "green"
  ]
}

To help us with the tests, we can create a function helper instantiating a schema and validating data. Let call it validate(). To instantiate a new JsonSchema object, the JsonSchema.create() static function can be invoked. Then, the JsonSchema.validate() method will be called to check if the data passed is correct.

void validate(Map<String, dynamic> schema, Map<String, dynamic> data, {String? msg}) {
  if (msg!=null) print("${msg}:");
  final _schema = JsonSchema.create(schema);
  final validate = _schema.validate(data);
  print("  ${validate}: ${data}");
  print("");
}

Before doing the whole specification for this object, we can start to specify only one of those fields, like the productId. json_schema module can use both a Map<String, dynamic> or a JSON<String> to load this. To make our life easier, we will create functions wrapper returning the schema we want as a Map.

Map<String, dynamic> _productId() {
  return {                                          
    "description": "The unique identifier for a product",
    "type": "integer",                              
  };                                                
}

A JSON schema describe an object and its properties. A productId is an integer. The description field is not used by the validator, it's only a way to help developers and designer to understand the structure. An object can be defined by many types:

  • null (e.g. null);

  • boolean (e.g. true or false);

  • number (e.g. 1 or -1.23);

  • integer (e.g 1 or 1024);

  • string (e.g. "test");

  • object (e.g. {});

  • array (e.g. []).

All of them are coming from the JSON specification itself.

Map<String, dynamic> _productName() {               
  return {                                          
    "description": "Name of the product",           
    "type": "string"                                
  };                                                
}

The productName is a string. Nothing complex here, the schema is similar to the productId object.

Map<String, dynamic> _price() {
  return {                                          
    "description": "The price of the product",
    "type": "number",                               
    "exclusiveMinimum": 0                           
  };                                                
}

A price is a number. To avoid negative numbers, we are also enforcing the specification with the exclusiveMinimum parameter. If a price is negative, the schema becomes invalid.

Map<String, dynamic> _tags() {
  return {                                          
    "description": "Tags for the product",
    "type": "array",                                
    "items": {                                      
      "type": "string"                              
    },                                              
    "minitems": 1,                                  
    "uniqueItems": true                             
  };                                                
}

Compound terms can also be created. The tags object is defined as an array or string. It must have at least 1 items (see minitems parameter) and must contain only unique items (see uniqueItems parameter).

Map<String, dynamic> _dimensions() {
  return {                                          
    "type": "object",                               
    "properties": {                                 
      "length": {                                   
        "type": "number"                            
      },                                            
      "width": {                                    
        "type": "number"                            
      },                                            
      "height": {                                   
        "type": "number"                            
      }                                             
    },                                              
    "required": [ "length", "width", "height" ]
  };                                                
}

Another object can be defined. It is also a compound term. In our case, the dimensions of an item must have a length as number, a width as number and a height as number too. All those fields are required (see required).

Map<String, dynamic> fullSchema() {
  return {
    "\$schema": "https://json-schema.org/draft/2020-12/schema",
    "\$id": "https://example.com/product.schema.json",
    "title": "Product",             
    "description": "A product in the catalog",
    "type": "object",
    "required": [  
      "productId",
      "productName",    
      "price",
    ],          
    "properties": {     
      "productId": _productId(),
      "productName": _productName(),
      "price": _price(),
      "tags": _tags(),
      "dimensions": _dimensions()
    }                                          
  };
}

Finally, the function fullSchema() is containing the whole JSON schema. Lot of fields here a kinda mandatory and are directly related to the JSON Schema specification. Let test that in our main entry-point.

void main(List<String> arguments) {
  validate(fullSchema(), {}, msg: "empty data");

  validate(fullSchema(), {
    "productId": 1
  }, msg: "productId only");

  validate(fullSchema(), {
    "productId": 1,
    "productName": "A green door",
    "price": 12.50
  }, msg: "minimal valid data");

  validate(fullSchema(), {
    "productId": 1,
    "productName": "A green door",
    "price": 12.50,
    "tags": [
      "home",
      "green"
    ]
  }, msg: "valid data with tags");

  validate(fullSchema(), {
    "productId": 1,
    "productName": "A green door",
    "price": 12.50,
    "tags": [
      "home",
      "green"
    ],
    "dimensions": {
      "length": 1,
      "width": 2,
      "height": 3,
    }
  }, msg: "valid data with tags and dimensions");
}

We can now run this application to see the result.

$ dart run
Resolving dependencies in `/tmp/dart/validate`... 
Downloading packages... 
Got dependencies in `/tmp/dart/validate`.
Building package executable... 
Built validate:validate.

empty data:
  INVALID, Errors: [# (root): required prop missing: productId from {}, /productId: required prop missing: productId from {}, # (root): required prop missing: productName from {}, /productName: required prop missing: productName from {}, # (root): required prop missing: price from {}, /price: required prop missing: price from {}]: {}

productId only:
  INVALID, Errors: [# (root): required prop missing: productName from {productId: 1}, /productName: required prop missing: productName from {productId: 1}, # (root): required prop missing: price from {productId: 1}, /price: required prop missing: price from {productId: 1}]: {productId: 1}

minimal valid data:
  VALID: {productId: 1, productName: A green door, price: 12.5}

valid data with tags:
  VALID: {productId: 1, productName: A green door, price: 12.5, tags: [home, green]}

valid data with tags and dimensions:
  VALID: {productId: 1, productName: A green door, price: 12.5, tags: [home, green], dimensions: {length: 1, width: 2, height: 3}}

As you can see, if the data received is missing some fields, the data is considered invalid. In other hands, if the requirements are there, the data is considered valid. Great, right? We now have a way to control the data received (or to control what we are sending).

Conclusion

Without approval and without scorn, but carefully studying the sentences word by word, one should trace them in the Discourses and verify them by the Discipline. If they are neither traceable in the Discourses nor verifiable by the Discipline, one must conclude thus: 'Certainly, this is not the Blessed One's utterance; this has been misunderstood by that bhikkhu - or by that community, or by those elders, or by that elder.' In that way, bhikkhus, you should reject it.
-- Siddharta Gautama

JSON Schema is a good way to make your application resilient and stable. It can be used as documentation tool, it will help to create tests, and it will also ensure the data received are legit. If you are working with public APIs, it can also help you to create the OpenAPI specifications. Finally, it will help you to design your application by thinking on what it needs, it will lead to a lean application containing only the necessary values.

JSON Schema can also be used to help us to reverse engineer private API interfaces by documenting what kind of data is working and which ones are not working. Creating specifications is great, Enjoy.

Wants to know more about JSON Schema? Here few interesting resources for you.

Happy Hack and Have fun!


Cover Image by Alex wong on Unsplash