Protobuf has native support for associative maps (dictionaries). However, there are strict rules for map keys and values:
- Keys: Can be any integral or string type. Messages, enums, floats, and bytes cannot be keys.
- Values: Can be any type, including another message, but cannot be another map or a repeated field.
Maps are just repeated messages with key and value fields, so older decoders can still read them.
Two entries, each written as its own little message on field 2. Entry order is not guaranteed to survive.
schema.proto
edition = "2024"; package demo.v1; message Project { string name = 1; map<string, string> labels = 2; map<uint32, string> port_names = 3; map<string, Contributor> contributors = 4; } message Contributor { string name = 1; uint32 commit_count = 2; }
Input JSON (editable)
ProtoJSON
Compiling the schema...
Next
Oneof
Using oneof in Protobuf for mutually exclusive fields: tagged-union semantics, how setting one member clears the others, and modeling polymorphic data.