This takes protobuf definitions and converts them into JSONSchemas, which can be used to dynamically validate JSON messages.
This will hopefully be useful for people who define their data using ProtoBuf, but use JSON for the "wire" format.
"Heavily influenced" by Google's protobuf-to-BigQuery-schema compiler.
GO111MODULE=on go get github.com/chrusty/protoc-gen-jsonschema/cmd/protoc-gen-jsonschema && go install github.com/chrusty/protoc-gen-jsonschema/cmd/protoc-gen-jsonschema
- About JSON Schema
- Popular GoLang JSON-Schema validation library
- Another GoLang JSON-Schema validation library
protoc-gen-jsonschema is designed to run like any other proto generator. The following examples show how to use options flags to enable different generator behaviours (more examples in the Makefile too).
- Allow NULL values (by default, JSONSchemas will reject NULL values unless we explicitly allow them):
protoc --jsonschema_out=allow_null_values:. --proto_path=testdata/proto testdata/proto/ArrayOfPrimitives.proto
- Disallow additional properties (JSONSchemas won't validate JSON containing extra parameters):
protoc --jsonschema_out=disallow_additional_properties:. --proto_path=testdata/proto testdata/proto/ArrayOfPrimitives.proto
- Disallow permissive validation of big-integers as strings (eg scientific notation):
protoc --jsonschema_out=disallow_bigints_as_strings:. --proto_path=testdata/proto testdata/proto/ArrayOfPrimitives.proto
- Prefix generated schema files with their package name (as a directory):
protoc --jsonschema_out=prefix_schema_files_with_package:. --proto_path=testdata/proto testdata/proto/ArrayOfPrimitives.proto
- Require all fields (because proto3 doesn't accommodate this):
protoc --jsonschema_out=all_fields_required:. --proto_path=testdata/proto testdata/proto/ArrayOfPrimitives.proto
- Enable debug logging:
protoc --jsonschema_out=debug:. --proto_path=testdata/proto testdata/proto/ArrayOfPrimitives.proto
- Proto with a simple (flat) structure: samples.PayloadMessage
- Proto containing a nested object (defined internally): samples.NestedObject
- Proto containing a nested message (defined in a different proto file): samples.NestedMessage
- Proto containing an array of a primitive types (string, int): samples.ArrayOfPrimitives
- Proto containing an array of objects (internally defined): samples.ArrayOfObjects
- Proto containing an array of messages (defined in a different proto file): samples.ArrayOfMessage
- Proto containing multi-level enums (flat and nested and arrays): samples.Enumception
- Proto containing a stand-alone enum: samples.ImportedEnum
- Proto containing 2 stand-alone enums: samples.FirstEnum, samples.SecondEnum
- Proto containing 2 messages: samples.FirstMessage, samples.SecondMessage