项目作者: chharvey

项目描述 :
JSON Schema validation for JSON-LD files using Schema.org vocabulary.
高级语言: TypeScript
项目地址: git://github.com/chharvey/schemaorg-jsd.git
创建时间: 2018-01-05T18:00:58Z
项目社区:https://github.com/chharvey/schemaorg-jsd

开源协议:MIT License

下载


schemaorg-jsd

JSON Schema validation for JSON-LD files using Schema.org vocabulary.

Usage

Install

  1. $ npm install schemaorg-jsd

Validate Against Schema.org JSON Schema

This module exports an asynchronous validation function.
It returns a Promise object, so you may use await or you may use standard Promise prototype methods.
Read the TypeDoc comments in ./src/index.ts for further details.

  1. const { sdoValidate } = require('schemaorg-jsd')
  2. async function run() {
  3. // example 1: use any javascript object
  4. const school = {
  5. '@context': 'http://schema.org/',
  6. '@type': 'Place',
  7. name: `Blacksburg, ${usState('Virginia').code}`,
  8. }
  9. school['@id'] = 'http://www.blacksburg.gov/'
  10. try {
  11. const is_valid_place = sdoValidate(school, 'Place') // validate against the `Place` schema
  12. console.log(await is_valid_place) // return `true` if the document passes validation
  13. } catch (err) { // throw a `TypeError` if the document fails validation
  14. console.error(err)
  15. console.error(err.filename) // file where the invalidation occurred
  16. console.error(err.details) // more json-schema specifics; see <https://github.com/epoberezkin/ajv#validation-errors>
  17. }
  18. // example 2: require a package
  19. const me = require('./me.json')
  20. console.log(await sdoValidate(me, 'Person')) // return `true` if the document passes validation
  21. // example 3: use a string (relative path) of the filename
  22. const org = './my-org.jsonld'
  23. console.log(await sdoValidate(org, 'Organization')) // return `true` if the document passes validation
  24. // example 4: infer the schema from the `'@type'` property
  25. await sdoValidate(school) // validates against the `Place` schema, since `school['@type'] === 'Place'`
  26. // example 5: multiple types
  27. const business = {
  28. '@context': 'http://schema.org/',
  29. '@type': ['Place', 'LocalBusiness'],
  30. }
  31. await sdoValidate(business) // validates against all schemata in the array
  32. // example 6: default type is `Thing` (http://schema.org/Thing)
  33. await sdoValidate({
  34. '@context': 'http://schema.org/',
  35. '@type': 'foobar' // validates against the `Thing` schema, since value 'foobar' cannot be found
  36. })
  37. await sdoValidate({
  38. '@context': 'http://schema.org/',
  39. // validates against the `Thing` schema, since property '@type' is missing
  40. })
  41. // example 7: pass options object to Ajv constructor
  42. // (see https://github.com/ajv-validator/ajv/blob/master/docs/api.md#options)
  43. await sdoValiate(data, type, {
  44. strict: true,
  45. });
  46. }

Validate Against Your Own JSON Schema

You can use ajv to validate any document against any JSON schema.
Normally you would do this by adding the schema to the ajv instance, and then checking the document.
However, if you write a schema that references one of this project’s Schema.org schema (via $ref),
you must add them both to the ajv instance.

Due to the interconnectedness of all Schema.org schemata, it’s faster to add them all at once.
This project’s exported SCHEMATA object is an array of Schema.org JSON schema,
pre-packaged and ready to add.

  1. const Ajv = require('ajv')
  2. const sdo_jsd = require('schemaorg-jsd')
  3. const my_schema = {
  4. "$schema": "http://json-schema.org/draft-07/schema#",
  5. "$id": "https://chharvey.github.io/example.jsd",
  6. "title": "Array<Thing>",
  7. "description": "An array of Schema.org Things.",
  8. "type": "array",
  9. "items": { "$ref": "https://chharvey.github.io/schemaorg-jsd/schema/Thing.jsd" }
  10. }
  11. const my_data = [
  12. { "@context": "http://schema.org/", "@type": "Thing", "name": "Thing 1" },
  13. { "@context": "http://schema.org/", "@type": "Thing", "name": "Thing 2" }
  14. ]
  15. async function run() {
  16. const ajv = new Ajv()
  17. .addMetaSchema(await sdo_jsd.META_SCHEMATA)
  18. .addSchema(await sdo_jsd.JSONLD_SCHEMA)
  19. .addSchema(await sdo_jsd.SCHEMATA)
  20. ajv.validate(my_schema, my_data)
  21. /*
  22. Note that the `Ajv#validate()` method’s parameters are reversed from this package’s `sdoValidate()`:
  23. Ajv#validate(schema, data) // schema comes before data
  24. sdoValidate(data, schemaTitle) // data comes before schema
  25. */
  26. }

View the “API”

This project includes a set of TypeDoc declarations describing types and their properties.
They’re identical to the specs at schema.org,
but you can import the source code in your own project for
TypeScript compilation.

View the docs.

  1. import * as sdo from 'schemaorg-jsd'
  2. class Person {
  3. /** This person’s name. */
  4. private _name: string;
  5. /**
  6. * Construct a new Person object.
  7. * @param jsondata an object validating against the schemaorg-jsd `Person` schema
  8. */
  9. constructor(jsondata: sdo.Person) {
  10. this._name = jsondata.name
  11. }
  12. }

Background Info

JSON

JSON (JavaScript Object Notation) is a data interchange format,
based off of the syntax used to define object literals in JavaScript.

JSON Schema

JSON Schema is a subset of JSON
that allows you to validate JSON documents.
In other words, a particular JSON schema tells you whether your JSON instance file is written correctly,
if you choose to validate your instance against that schema.
JSON schema documents themselves must also be valid JSON, as well as validate against the
JSON Meta-Schema specification.
The JSON Meta-Schema tells you whether your JSON schema document, if you have one, is written correctly.
The official MIME Type of JSON schema documents is application/schema+json.

Note: this project uses a .jsd (“JSON Schema Definition”) file extension to name JSON schema files, though
there is no prevailing convention on JSON schema file extensions.

JSON-LD

JSON-LD (JSON Linked Data) is a syntax used to mark up data in a consistent way.
Rather than everyone using their own data types, JSON-LD standardizes the markup, making it easy
for people and data types to communicate.
JSON-LD has some rules, for example, an object’s @id property must be a string.
Therefore, to enforce these rules, JSON-LD documents should validate against the
JSON-LD Schema.
The official MIME Type of JSON-LD documents is application/ld+json,
and JSON-LD files typically have file extension .jsonld.

Schema.org

Schema.org Is a vocabulary that you can use to describe data.
These are semantic descriptions that have well-defined meanings.
For example, people using different human languages could refer to the unique identifier http://schema.org/givenName
and know precisely what others are talking about: a person’s given name.
The Schema.org vocabulary is syntax-agnostic, meaning you can use whatever format you want to mark up your data.
Microdata is one common syntax, and JSON-LD is another.

TypeScript

TypeScript is a strongly-typed language that compiles to JavaScript.
Some of the biggest features of TypeScript include interfaces and type aliases, which, respectively,
describe the “shape” (fields and methods) and “structure” (properties) that an object may have.
This project includes interfaces and type aliases for Schema.org Classes and Properties, respectively,
so that you can write a well-typed API for your project.

Putting It All Together

You can semantically mark up your data using the Schema.org vocabulary with JSON-LD syntax.
If you have a TypeScript API, you can import this project’s TypeScript to catch any type errors before runtime.
Then, to prevent additional runtime errors or SEO mistakes, you can validate your markup against
the JSON schemata in this project.