Giter Site home page Giter Site logo

kaptinlin / jsonschema Goto Github PK

View Code? Open in Web Editor NEW
26.0 2.0 4.0 276 KB

A powerful Go JSON Schema validator library aligned with the JSON Schema Draft 2020-12. It features enhanced validation outputs and supports internationalization, making it perfect for developers requiring comprehensive schema compliance and multilingual error messaging in modern applications.

License: MIT License

Go 99.29% Makefile 0.71%
jsonschema jsonschema-validator validation validator

jsonschema's Introduction

JsonSchema Validator for Go

This library provides robust JSON Schema validation for Go applications, designed to support the latest specifications of JSON Schema. This validator aligns with JSON Schema Draft 2020-12, implementing a modern approach to JSON schema validation.

Table of Contents

Features

  • Latest JSON Schema Support: Compliant with JSON Schema Draft 2020-12. This library does not support earlier versions of JSON Schema.
  • Passed All JSON Schema Test Suite Cases: Successfully passes all the JSON Schema Test Suite cases for Draft 2020-12, except those involving vocabulary.
  • Internationalization Support: Includes capabilities for internationalized validation messages. Supports multiple languages including English (en), German (de-DE), Spanish (es-ES), French (fr-FR), Japanese (ja-JP), Korean (ko-KR), Portuguese (pt-BR), Simplified Chinese (zh-Hans), and Traditional Chinese (zh-Hant).
  • Enhanced Validation Output: Implements enhanced output for validation errors as proposed in recent JSON Schema updates.
  • Performance Enhancement: Uses github.com/goccy/go-json instead of encoding/json to improve performance.

Installation

Ensure your Go environment is set up (requires Go version 1.21.1 or higher) and install the library:

go get github.com/kaptinlin/jsonschema

Quickstart

Here is a simple example to demonstrate compiling a schema and validating an instance:

import (
    "github.com/kaptinlin/jsonschema"
    "github.com/goccy/go-json"
)

func main() {
	schemaJSON := `{
		"type": "object",
		"properties": {
			"name": {"type": "string"},
			"age": {"type": "integer", "minimum":20}
		},
		"required": ["name", "age"]
	}`

	compiler := jsonschema.NewCompiler()
	schema, err := compiler.Compile([]byte(schemaJSON))
	if err != nil {
		log.Fatalf("Failed to compile schema: %v", err)
	}

	instance := map[string]interface{}{
		"name": "John Doe",
		"age":  19,
	}
	result := schema.Validate(instance)
	if !result.IsValid() {
		details, _ := json.MarshalIndent(result.ToList(), "", "  ")
		fmt.Println(string(details))
	}
}

This example will output the following:

{
  "valid": false,
  "evaluationPath": "",
  "schemaLocation": "",
  "instanceLocation": "",
  "errors": {
    "properties": "Property 'age' does not match the schema"
  },
  "details": [
    {
      "valid": true,
      "evaluationPath": "/properties/name",
      "schemaLocation": "#/properties/name",
      "instanceLocation": "/name"
    },
    {
      "valid": false,
      "evaluationPath": "/properties/age",
      "schemaLocation": "#/properties/age",
      "instanceLocation": "/age",
      "errors": {
        "minimum": "19 should be at least 20"
      }
    }
  ]
}

Output Formats

The library supports three output formats:

  • Flag: Provides a simple boolean indicating whether the validation was successful.
    result.ToFlag()
  • List: Organizes all validation results into a top-level list.
    result.ToList()
  • Hierarchical: Organizes validation results into a hierarchy mimicking the schema structure.
    result.ToList(false)

Loading Schema from URI

The compiler.GetSchema method allows loading a JSON Schema directly from a URI, which is especially useful for utilizing shared or standard schemas:

metaSchema, err := compiler.GetSchema("https://json-schema.org/draft/2020-12/schema")
if err != nil {
    log.Fatalf("Failed to load meta-schema: %v", err)
}

Multilingual Error Messages

The library supports multilingual error messages through the integration with github.com/kaptinlin/go-i18n. Users can customize the localizer to support additional languages:

i18n, err := jsonschema.GetI18n()
if err != nil {
	log.Fatalf("Failed to get i18n: %v", err)
}
localizer := i18n.NewLocalizer("zh-Hans")

result := schema.Validate(instance)
if !result.IsValid() {
    details, _ := json.MarshalIndent(result.ToLocalizeList(localizer), "", "  ")
    log.Println(string(details))
}

Setup Test Environment

This library uses a git submodule to include the official JSON Schema Test Suite for thorough validation. Setting up your test environment is simple:

  1. Initialize Submodule:

    • In your terminal, navigate to your project directory.
    • Run: git submodule update --init --recursive
  2. Run Tests:

    • Change directory to tests: cd tests
    • Run standard Go test command: go test

How to Contribute

Contributions to the jsonschema package are welcome. If you'd like to contribute, please follow the contribution guidelines.

Recommended JSON Schema Libraries

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

Special thanks to the creators of jsonschema by santhosh-tekuri and Json-Everything for inspiring and supporting the development of this library.

jsonschema's People

Contributors

dependabot[bot] avatar guochengh avatar kaptinlin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

jsonschema's Issues

Value error with nested type on interface{}

I'm getting a validation error when using a map[string]interface{} as the value.

Here's the example:

Json Schema

{
  "$id": "https://example.com/blog-post.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "A representation of a blog post",
  "type": "object",
  "required": ["title", "content", "author"],
  "properties": {
    "title": {
      "type": "string"
    },
    "content": {
      "type": "string"
    },
    "publishedDate": {
      "type": "string",
      "format": "date-time"
    },
    "author": {
      "$ref": "https://example.com/user-profile.schema.json"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  }
}

The data

data := map[string]interface{}{
  "title":         "New Blog Post",
  "content":       "This is the content of the blog post...",
  "publishedDate": "2023-08-25T15:00:00Z",
  "author": map[string]interface{}{
	  "username": "authoruser",
	  "email":    "[email protected]",
  },
  "tags": []string{"Technology", "Programming"},
}

Error:
"/tags"
"Value is unknown but should be array"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.