패키지, 저장소 및 앱 카테고리 검색

패키지 상세v5.2.2

json_schema

Dart에서의 JSON 스키마 구현

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
22.4만
좋아요
45
Pub 점수
115

패키지 설치

flutter pub add json_schema

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

JSON 스키마의 다트 구현체로, 스키마 정의에 기반하여 JSON 데이터의 검증, 파싱 및 생성을 가능하게 합니다. JSON 객체의 구조, 유형 및 제약 조건을 정의하고 강제함으로써 데이터 무결성을 보장하는 강력한 방법을 제공합니다. 이 패키지는 정적 및 동적 스키마 평가를 모두 지원하며, 다양한 플랫폼에서 엄격한 데이터 검증이 필요한 애플리케이션에 적합합니다. 플러터 및 기타 다트 기반 프로젝트와 원활하게 통합됩니다.

사용 사례

  • API 응답 검증
  • 폼에서 데이터 구조 강제 적용
  • 스키마 템플릿에서 JSON 생성
  • 백엔드 데이터 계약과의 통합
  • JSON 페이로드 테스트
  • 동적 폼 생성

주요 기능

  • 세부 오류 메시지가 있는 스키마 검증
  • 복잡한 중첩 스키마 지원
  • JSON과 Dart 간의 직렬화 및 역직렬화
  • 확장 가능한 검증 규칙
  • 크로스 플랫폼 호환성
  • 내장 스키마 해석

적합한 대상

  • 데이터 검증이 필요한 API 클라이언트
  • 동적 스키마를 가진 폼 빌더
  • 백엔드 통합 도구
  • 데이터 기반 UI
  • 테스트 프레임워크
  • 구성 관리 시스템

고려 사항

  • JSON 스키마 사양을 이해해야 합니다
  • 깊이 중첩된 스키마의 성능 영향
  • 확장 없이 사용자 정의 검증기의 내장 지원이 제한적
  • 대규모 스키마 세트에 대한 추가 설정이 필요할 수 있습니다
  • 실시간 스키마 편집을 위한 설계가 아님

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

JSON Schema

A platform agnostic (web, flutter or vm) Dart library for validating JSON instances against JSON Schemas (multi-version support with latest of Draft 7).

Getting Started

  1. Ensure you have latest stable Dart installed.
  2. make pubget
  3. make format
  4. make analyze
  5. make test-with-serve-remotes
Alternative Test Running Strategy (To run specific tests, or pass other args to dart test):
  1. make serve-remotes (in a separate terminal tab - HTTP fixtures need to be served for tests to pass)
  2. make test or dart test -n <YOUR TEST>
  3. SIGINT your make serve-remotes tab or run make stop-serve-remotes

Note: For convenience, make stop-serve-remotes will be run as a prerequisite before make test-with-serve-remotes and make serve-remotes

Updating Test Fixtures
  1. make gen-fixtures Generates Dart source files that contain the JSON-Schema-Test-Suite tests and fixtures for use in cross-platform testing that doesn't require dart:io to read the files on disk.
  2. Commit the results of generation, if any.

Note: CI runs make gen-fixtures --check to ensure these are up-to-date on each

Simple Example Usage

The simplest way to create a schema is to pass JSON data directly to JsonSchema.create with a JSON String, or decoded JSON via Dart Map or bool.

After creating any schema, JSON instances can be validated by calling .validate(instance) on that schema. By default, instances are expected to be pre-parsed JSON as native dart primitives (Map, List, String, bool, num, int). You can also optionally parse at validation time by passing in a string and setting parseJson: schema.validate('{ "name": "any JSON object"}', parseJson: true).

Note: Creating JsonSchemas synchronously implies access to all $refs within the root schema. If you don't have access to all this data at the time of the construction, see "Asynchronous Creation" examples below.

import 'package:json_schema/json_schema.dart';

main() {
  /// Define schema in a Dart [Map] or use a JSON [String].
  final mustBeIntegerSchemaMap = {"type": "integer"};

  // Create some examples to validate against the schema.
  final n = 3;
  final decimals = 3.14;
  final str = 'hi';

  // Construct the schema from the schema map or JSON string.
  final schema = JsonSchema.create(mustBeIntegerSchemaMap);

  print('$n => ${schema.validate(n)}'); // true
  print('$decimals => ${schema.validate(decimals)}'); // false
  print('$str => ${schema.validate(str)}'); // false
}

Or see json_schema/example/readme/synchronous_creation/self_contained.dart

And run dart run ./example/readme/synchronous_creation/self_contained.dart

Advanced Usage

Synchronous Creation, Local Ref Cache

If you want to create JsonSchemas synchronously, and you have $refs that cannot be resolved within the root schema, but you have a cache of those $ref'd schemas locally, you can write a RefProvider to get them during schema evaluation.

See json_schema/example/readme/synchronous_creation/local_ref_cache.dart

Or run dart run ./example/readme/synchronous_creation/local_ref_cache.dart

Asynchronous Creation, Remote HTTP Refs

If you have schemas that have nested $refs that are HTTP URIs that are publicly accessible, you can use Future<JsonSchema> JsonSchema.createAsync and the references will be fetched as needed during evaluation. You can also use JsonSchema.createFromUrl if you want to fetch the root schema remotely as well (see next example).

See json_schema/example/readme/asynchronous_creation/remote_http_refs.dart

Or run dart run ./example/readme/asynchronous_creation/remote_http_refs.dart

Asynchronous Creation, From URL or File

You can also create a schema directly from a publicly accessible URL or File.

URLs

See json_schema/example/readme/asynchronous_creation/from_url.dart

Or run dart run ./example/readme/asynchronous_creation/from_url.dart

Files

See json_schema/example/readme/asynchronous_creation/from_file.dart

Or run dart run ./example/readme/asynchronous_creation/from_file.dart

Asynchronous Creation, with custom remote $refs:

If you have nested $refs that are either non-HTTP URIs or non-publicly-accessible HTTP $refs, you can supply an async RefProvider to createAsync, and perform any custom logic you need.

See json_schema/example/readme/asynchronous_creation/remote_ref_cache.dart

Or run dart run ./example/readme/asynchronous_creation/remote_ref_cache.dart

How To Use Schema Information

Schema information can be used for validation; but it can also be a valuable source of information about the structure of data. The JsonSchema class fully parses the schema first, which itself must be valid on all paths within the schema. Accessors are provided for all specified keywords of the JSON Schema specification associated with a schema, so tools can use it to create rich views of the data, like forms or diagrams.

카테고리

의존성

의존성 목록 5 개

소스 저장소

이 패키지를 사용하는 프로젝트