Viewing version 2.0.1. Open the latest package page.

json_schema

2.0.1

Provide support for validating instances against json schema

Download archive

Readme

JSON Schema

A platform agnostic (dart:html or dart:io) Dart library for validating JSON instances against JSON Schemas (multi-version support with latest of Draft 6).

Build Status

How To Create and Validate Against a Schema

Synchronous Creation - Self Contained

The simplest way to create a schema is to pass JSON data directly to JsonSchema.createSchema 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.

Example

A schema can be created with a Map that is either hand-crafted, referenced from a JSON file, or previously fetched from the network or file system.

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.createSchema(mustBeIntegerSchemaMap);

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

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.

Example

import 'package:json_schema/json_schema.dart';
import 'package:dart2_constant/convert.dart';

main() {
  final referencedSchema = {
    r"$id": "https://example.com/geographical-location.schema.json",
    r"$schema": "http://json-schema.org/draft-06/schema#",
    "title": "Longitude and Latitude",
    "description": "A geographical coordinate on a planet (most commonly Earth).",
    "required": ["latitude", "longitude"],
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "latitude": {"type": "number", "minimum": -90, "maximum": 90},
      "longitude": {"type": "number", "minimum": -180, "maximum": 180}
    }
  };

  final RefProvider refProvider = (String ref) {
    final Map references = {
      'https://example.com/geographical-location.schema.json': JsonSchema.createSchema(referencedSchema),
    };

    if (references.containsKey(ref)) {
      return references[ref];
    }

    return null;
  };

  final schema = JsonSchema.createSchema({
    'type': 'array',
    'items': {r'$ref': 'https://example.com/geographical-location.schema.json'}
  }, refProvider: refProvider);

  final workivaLocations = [
    {
      'name': 'Ames',
      'latitude': 41.9956731,
      'longitude': -93.6403663,
    },
    {
      'name': 'Scottsdale',
      'latitude': 33.4634707,
      'longitude': -111.9266617,
    }
  ];

  final badLocations = [
    {
      'name': 'Bad Badlands',
      'latitude': 181,
      'longitude': 92,
    },
    {
      'name': 'Nowhereville',
      'latitude': -2000,
      'longitude': 7836,
    }
  ];

  print('${json.encode(workivaLocations)} => ${schema.validate(workivaLocations)}');
  print('${json.encode(badLocations)} => ${schema.validate(badLocations)}');
}

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.createSchemaAsync and the references will be fetched as needed during evaluation. You can also use JsonSchema.createSchemaFromUrl if you want to fetch the root schema remotely as well (see next example).

Example

import 'dart:io';

import 'package:json_schema/json_schema.dart';

// For VM:
import 'package:json_schema/vm.dart';

// For Browser:
// import 'package:json_schema/browser.dart';

main() async {
  // For VM:
  configureJsonSchemaForVm();

  // For Browser:
  // configureJsonSchemaForBrowser();

  // Schema Defined as a JSON String
  final schema = await JsonSchema.createSchemaAsync(r'''
  {
    "type": "array",
    "items": {
      "$ref": "https://raw.githubusercontent.com/json-schema-org/JSON-Schema-Test-Suite/master/remotes/integer.json"
    }
  }
  ''');

  // Create some examples to validate against the schema.
  final numbersArray = [1, 2, 3];
  final decimalsArray = [3.14, 1.2, 5.8];
  final strArray = ['hello', 'world'];

  print('$numbersArray => ${schema.validate(numbersArray)}'); // true
  print('$decimalsArray => ${schema.validate(decimalsArray)}'); // false
  print('$strArray => ${schema.validate(strArray)}'); // false

  // Exit the process cleanly (VM Only).
  exit(0);
}

Asynchronous Creation, From URL or File

You can also create a schema directly from a publicly accessible URL, like so:

Example 1 - URL

import 'dart:io';

import 'package:json_schema/json_schema.dart';

// For VM:
import 'package:json_schema/vm.dart';

// For Browser:
// import 'package:json_schema/browser.dart';

main() async {
  // For VM:
  configureJsonSchemaForVm();

  // For Browser:
  // configureJsonSchemaForBrowser();

  final url = "https://raw.githubusercontent.com/json-schema-org/JSON-Schema-Test-Suite/master/remotes/integer.json";

  final schema = await JsonSchema.createSchemaFromUrl(url);

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

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

  // Exit the process cleanly (VM Only).
  exit(0);
}

Example 2 - File

import 'dart:io';

import 'package:json_schema/json_schema.dart';

// For VM:
import 'package:json_schema/vm.dart';

// For Browser:
// import 'package:json_schema/browser.dart';

main() async {
  // For VM:
  configureJsonSchemaForVm();

  // For Browser:
  // configureJsonSchemaForBrowser();

  final file = "example/readme/asynchronous_creation/geo.schema.json";

  final schema = await JsonSchema.createSchemaFromUrl(file);

  // Create some examples to validate against the schema.
  final workivaAmes = {
    'latitude': 41.9956731,
    'longitude': -93.6403663,
  };

  final nowhereville = {
    'latitude': -2000,
    'longitude': 7836,
  };

  print('$workivaAmes => ${schema.validate(workivaAmes)}'); // true
  print('$nowhereville => ${schema.validate(nowhereville)}'); // false

  // Exit the process cleanly (VM Only).
  exit(0);
}

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 RefProviderAsync to createSchemaAsync, and perform any custom logic you need.

Example

import 'dart:io';
import 'dart:async';
import 'package:dart2_constant/convert.dart';

import 'package:json_schema/json_schema.dart';

// For VM:
import 'package:json_schema/vm.dart';

// For Browser:
// import 'package:json_schema/browser.dart';

main() async {
  // For VM:
  configureJsonSchemaForVm();

  // For Browser:
  // configureJsonSchemaForBrowser();

  final referencedSchema = {
    r"$id": "https://example.com/geographical-location.schema.json",
    r"$schema": "http://json-schema.org/draft-06/schema#",
    "title": "Longitude and Latitude",
    "description": "A geographical coordinate on a planet (most commonly Earth).",
    "required": ["latitude", "longitude"],
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "latitude": {"type": "number", "minimum": -90, "maximum": 90},
      "longitude": {"type": "number", "minimum": -180, "maximum": 180}
    }
  };

  final RefProviderAsync refProvider = (String ref) async {
    final Map references = {
      'https://example.com/geographical-location.schema.json': JsonSchema.createSchema(referencedSchema),
    };

    if (references.containsKey(ref)) {
      // Silly example that adds a 1 second delay.
      // In practice, you could make any service call here,
      // parse the results into a schema, and return.
      await new Future.delayed(new Duration(seconds: 1));
      return references[ref];
    }

    // Fall back to default URL $ref behavior
    return await JsonSchema.createSchemaFromUrl(ref);
  };

  final schema = await JsonSchema.createSchemaAsync({
    'type': 'array',
    'items': {r'$ref': 'https://example.com/geographical-location.schema.json'}
  }, refProvider: refProvider);

  final workivaLocations = [
    {
      'name': 'Ames',
      'latitude': 41.9956731,
      'longitude': -93.6403663,
    },
    {
      'name': 'Scottsdale',
      'latitude': 33.4634707,
      'longitude': -111.9266617,
    }
  ];

  final badLocations = [
    {
      'name': 'Bad Badlands',
      'latitude': 181,
      'longitude': 92,
    },
    {
      'name': 'Nowhereville',
      'latitude': -2000,
      'longitude': 7836,
    }
  ];

  print('${json.encode(workivaLocations)} => ${schema.validate(workivaLocations)}');
  print('${json.encode(badLocations)} => ${schema.validate(badLocations)}');

  exit(0);
}

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.

One example use is the deprecated schemadot program included in the bin folder which takes schema as input and outputs a Graphviz dot file, providing a picture of the schema. This does not provide all information of the schema, and is a work in progress - but it can be useful to see what a schema is.

For example, the grades_schema.json is:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title" : "Grade Tracker",
    "type" : "object",
    "additionalProperties" : false,
    "properties" : {
	"semesters" : {
	    "type" : "array",
	    "items" : {
                "type" : "object",
                "additionalProperties" : false,
                "properties" : {
                    "semester": { "type" : "integer" },
                    "grades" : {
                        "type" : "array",
                        "items" : {
                            "type" : "object",
                            "additionalProperties" : false,
                            "required" : [ "date", "type", "grade", "std" ],
                            "properties" : {
                                "date" : { "type" : "string"},
                                "type" : { "enum" : [ "homework", "quiz", "test", "final_exam" ] },
                                "grade" : { "type" : "number"},
                                "std" : { 
                                    "oneOf" : [ 
                                        {"type" : "number"}, 
                                        {"type" : "null"}
                                    ] 
                                },
                                "avg" : { 
                                    "oneOf" : [ 
                                        {"type" : "number"}, 
                                        {"type" : "null"}
                                    ] 
                                }
                            }
                        }
                    }
                }
            }
  	    }
    }
}

And the generated image is:

Grades!

For more detailed image open link: Grade example schema diagram

Changelog

2.0.0

  • json_schema is no longer bound to dart:io and works in the browser!
  • Full JSON Schema draft6 compatibility
  • Much better $ref resolution, including deep nesting of $refs
  • More typed keyword getters for draft6 like examples
  • Syncronous schema evaluation by default
  • Optional async evaluation and fetching with createSchemaAsync
  • Automatic parsing of JSON strings passed to createSchema and createSchemaAsync
  • Ability to do custom resolution of $refs with RefProvider and RefProviderAsync
  • Optional parsing of JSON strings passed to validate with parseJson = true
  • Dart 2.0 compatibility
  • Many small changes to make things more in line with modern dart.
  • Please see the migration guide for additional info.

1.0.8

  • Code cleanup
  • Strong mode
  • Switch build tools to dart_dev

1.0.7

  • Update dependency constraint on the args package.

1.0.3

  • Add a dependency on the args package.

1.0.2

  • Add a dependency on the logging package.

Installing

export PUB_HOSTED_URL=https://pub.mirror.p-hatan.ir
flutter pub add 'json_schema:2.0.1'
pubspec.yaml
name: json_schema
version: 2.0.1
description: Provide support for validating instances against json schema
authors:
  - Michael Carter <michael.carter@workiva.com>
  - Daniel Davidson <dbdavidson@yahoo.com>
homepage: https://github.com/workiva/json_schema

environment:
  sdk: ">=1.24.3 <3.0.0"

dependencies:
  args: ">=0.13.7 <2.0.0"
  dart2_constant: ^1.0.0
  logging: ">=0.9.3 <0.12.0"
  path: ^1.3.0
  uri: ">=0.11.1 <0.12.0"
  w_transport: ^3.2.8

dev_dependencies:
  build_runner: ">=0.6.0 <2.0.0"
  build_test: ">=0.9.0 <2.0.0"
  build_web_compilers: ">=0.2.0 <2.0.0"
  coverage: ">=0.10.0 <0.13.0"
  dart_dev: ^2.0.0
  dart_style: ^1.0.9
  dependency_validator: ^1.2.1
  shelf: ^0.7.2
  shelf_static: ^0.2.7
  test: ">=0.12.30 <2.0.0"

Version history

VersionPublishedArchiveSHA-256
0.0.1Cached · Upstream SHA-256 matchedDownload6e971894…ba8d04
0.0.2Cached · Upstream SHA-256 matchedDownload830a3456…dfe101
1.0.0Cached · Upstream SHA-256 matchedDownload3a945c9a…f3d551
1.0.1Cached · Upstream SHA-256 matchedDownload928b3024…20c89b
1.0.2Cached · Upstream SHA-256 matchedDownloadfe7c4b2a…d1fe7a
1.0.3Cached · Upstream SHA-256 matchedDownload0f19f647…d2fcd3
1.0.4Cached · Upstream SHA-256 matchedDownload32746b07…75f861
1.0.5Cached · Upstream SHA-256 matchedDownloadbf4e3762…cf3f67
1.0.6Cached · Upstream SHA-256 matchedDownload0e37180c…021ae1
1.0.7Cached · Upstream SHA-256 matchedDownload6dafff24…f5de64
1.0.8Cached · Upstream SHA-256 matchedDownload09f61ada…b00371
1.0.9Cached · Upstream SHA-256 matchedDownloadd34cdf92…eeee52
1.0.10Cached · Upstream SHA-256 matchedDownload7cd7d0fb…f06ce6
2.0.0-RC1Cached · Upstream SHA-256 matchedDownload958f7471…3614ac
2.0.0-RC2Cached · Upstream SHA-256 matchedDownload9771c5e7…8d6157
2.0.0-RC3Cached · Upstream SHA-256 matchedDownload337ee155…fc9a20
2.0.0Cached · Upstream SHA-256 matchedDownloadd6c7f992…f60bf8
2.0.1Cached · Upstream SHA-256 matchedDownload0f59efb9…fb6816
2.1.0Cached · Upstream SHA-256 matchedDownload8f9a5eb7…48c841
2.1.2Cached · Upstream SHA-256 matchedDownload7896f5da…737f4f
2.1.3Cached · Upstream SHA-256 matchedDownload39054a75…6cda3b
2.1.4Cached · Upstream SHA-256 matchedDownload1d2c28bb…84deb8
2.2.0Cached · Upstream SHA-256 matchedDownload811b34af…e03d7d
2.2.1Cached · Upstream SHA-256 matchedDownload345c478b…83f092
3.0.0Cached · Upstream SHA-256 matchedDownloadb8bf0e77…a7d1fe
3.0.1Cached · Upstream SHA-256 matchedDownload3a316f9e…0712c2
3.1.0Cached · Upstream SHA-256 matchedDownload5ce9cc98…057efc
3.1.1Cached · Upstream SHA-256 matchedDownload0e2cba88…827f82
3.2.0Cached · Upstream SHA-256 matchedDownload0e904e06…7f4fff
3.2.1Cached · Upstream SHA-256 matchedDownloaddefa58d4…0d4550
4.0.0-rc.1Cached · Upstream SHA-256 matchedDownload43c05020…e2211b
4.0.0-rc.2Cached · Upstream SHA-256 matchedDownload61f6ce6f…0c415e
4.0.0Cached · Upstream SHA-256 matchedDownload1ef01d65…2af7bc
4.0.1Cached · Upstream SHA-256 matchedDownload69e94786…886216
4.0.2Cached · Upstream SHA-256 matchedDownload5243b69c…971efb
4.0.3Cached · Upstream SHA-256 matchedDownloaddd50e239…e65896
4.0.4Cached · Upstream SHA-256 matchedDownloade83eb104…225caa
5.0.0-rc2Cached · Upstream SHA-256 matchedDownload9d81fde1…0759f8
5.0.0Cached · Upstream SHA-256 matchedDownloadd2d7b524…7807ad
5.1.0Cached · Upstream SHA-256 matchedDownloadb8df4801…30e6e0
5.1.1Cached · Upstream SHA-256 matchedDownloadd9325bc3…6838d9
5.1.2Cached · Upstream SHA-256 matchedDownload0fa8e7ba…bdd17b
5.1.3Cached · Upstream SHA-256 matchedDownload0a5f510e…4f6c7d
5.1.4Cached · Upstream SHA-256 matchedDownload7b3d4321…787046
5.1.5Cached · Upstream SHA-256 matchedDownload0df75856…c1bccc
5.1.6Cached · Upstream SHA-256 matchedDownload58d4c200…c00933
5.1.7Cached · Upstream SHA-256 matchedDownloadf1bcf816…62f358
5.2.0Cached · Upstream SHA-256 matchedDownloadb183ba82…d0a2cf
5.2.1Cached · Upstream SHA-256 matchedDownloadfc8c3e28…f20382
5.2.2Cached · Upstream SHA-256 matchedDownloadf37d9c3f…43fa1a

Dependencies

args "\u003e=0.13.7 \u003c2.0.0"

dart2_constant "^1.0.0"

logging "\u003e=0.9.3 \u003c0.12.0"

path "^1.3.0"

uri "\u003e=0.11.1 \u003c0.12.0"

w_transport "^3.2.8"