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.
- Features
- Installation
- Quickstart
- Output Formats
- Loading Schema from URI
- Multilingual Error Messages
- Setup Test Environment
- How to Contribute
- License
- 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.
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
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"
}
}
]
}
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)
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)
}
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))
}
This library uses a git submodule to include the official JSON Schema Test Suite for thorough validation. Setting up your test environment is simple:
-
Initialize Submodule:
- In your terminal, navigate to your project directory.
- Run:
git submodule update --init --recursive
-
Run Tests:
- Change directory to
tests
:cd tests
- Run standard Go test command:
go test
- Change directory to
Contributions to the jsonschema
package are welcome. If you'd like to contribute, please follow the contribution guidelines.
- quicktype: Generating code from JSON schema.
- hyperjump-io/json-schema: TypeScript version of JSON Schema Validation, Annotation, and Bundling. Supports Draft 04, 06, 07, 2019-09, 2020-12, OpenAPI 3.0, and OpenAPI 3.1.
- swaggest/jsonschema-go: JSON Schema structures for Go.
This project is licensed under the MIT License - see the LICENSE file for details.
Special thanks to the creators of jsonschema by santhosh-tekuri and Json-Everything for inspiring and supporting the development of this library.