A protoc plugin that generates json.Marshaler and json.Unmarshaler implementations for Go protobuf messages.
- 🚀 Lightweight - Generates clean and efficient code
- 🔄 Recursive Support - Automatically handles nested message types
- ✅ Standard Compatible - Uses official
protojsonpackage for compatibility - ⚙️ Configurable - Supports multiple customization options
- 📦 Proto3 Optional - Supports proto3 optional feature
go install github.com/pubgo/protoc-gen-go-json@latestprotoc --go_out=. --go-json_out=. your_proto_file.protoAdd to your buf.gen.yaml:
version: v2
plugins:
- local: protoc-gen-go
out: gen
opt: paths=source_relative
- local: protoc-gen-go-json
out: gen
opt:
- paths=source_relative| Option | Default | Description |
|---|---|---|
enums_as_ints |
false |
Render enums as integers instead of strings |
emit_defaults |
false |
Render fields with zero values |
orig_name |
false |
Use original (.proto) name for fields |
allow_unknown |
false |
Allow messages to contain unknown fields when unmarshaling |
debug |
false |
Enable debug mode |
protoc --go-json_out=emit_defaults=true,orig_name=true:. your_proto_file.protoFor the following protobuf definition:
message User {
string name = 1;
int32 age = 2;
}The plugin generates:
// MarshalJSON implements json.Marshaler
func (msg *User) MarshalJSON() ([]byte, error) {
return protojson.MarshalOptions{
UseEnumNumbers: false,
EmitUnpopulated: false,
UseProtoNames: false,
}.Marshal(msg)
}
// UnmarshalJSON implements json.Unmarshaler
func (msg *User) UnmarshalJSON(b []byte) error {
return protojson.UnmarshalOptions{
DiscardUnknown: false,
}.Unmarshal(b, msg)
}By default, Go structs generated by protoc-gen-go don't implement the standard library's json.Marshaler and json.Unmarshaler interfaces. This means that using the encoding/json package may result in field names and enum values being serialized in a way that doesn't conform to the protobuf JSON mapping specification.
The code generated by this plugin uses the official protojson package, ensuring:
- Field names follow protobuf JSON mapping specification
- Enum values are serialized as strings by default
- Proper handling of
oneof,optional, and other special fields - Consistency with protobuf JSON implementations in other languages
- Go 1.21+
- google.golang.org/protobuf