blob: d55786e18daad5770ca8a2602569617b63ffd736 [file] [log] [blame]
Herbie Ong7b828bc2019-02-08 19:56:24 -08001// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Damien Neil5c5b5312019-05-14 12:44:37 -07005package protojson
Herbie Ong7b828bc2019-02-08 19:56:24 -08006
7import (
8 "encoding/base64"
Herbie Ong0b0f4032019-03-18 19:06:15 -07009 "fmt"
Herbie Ong7b828bc2019-02-08 19:56:24 -080010 "sort"
11
Damien Neile89e6242019-05-13 23:55:40 -070012 "google.golang.org/protobuf/internal/encoding/json"
Joe Tsai5ae10aa2019-07-11 18:23:08 -070013 "google.golang.org/protobuf/internal/encoding/messageset"
14 "google.golang.org/protobuf/internal/errors"
15 "google.golang.org/protobuf/internal/flags"
Damien Neile89e6242019-05-13 23:55:40 -070016 "google.golang.org/protobuf/internal/pragma"
17 "google.golang.org/protobuf/proto"
18 pref "google.golang.org/protobuf/reflect/protoreflect"
19 "google.golang.org/protobuf/reflect/protoregistry"
Herbie Ong7b828bc2019-02-08 19:56:24 -080020)
21
22// Marshal writes the given proto.Message in JSON format using default options.
23func Marshal(m proto.Message) ([]byte, error) {
24 return MarshalOptions{}.Marshal(m)
25}
26
27// MarshalOptions is a configurable JSON format marshaler.
28type MarshalOptions struct {
29 pragma.NoUnkeyedLiterals
Herbie Ong984e5282019-09-06 00:29:48 -070030 encoder *json.Encoder
Herbie Ong7b828bc2019-02-08 19:56:24 -080031
Herbie Ong329be5b2019-03-27 14:47:59 -070032 // AllowPartial allows messages that have missing required fields to marshal
33 // without returning an error. If AllowPartial is false (the default),
34 // Marshal will return error if there are any missing required fields.
35 AllowPartial bool
36
Herbie Ong9111f3b2019-09-06 14:35:09 -070037 // UseEnumNumbers emits enum values as numbers.
38 UseEnumNumbers bool
39
Herbie Ong984e5282019-09-06 00:29:48 -070040 // EmitUnpopulated specifies whether to emit unpopulated fields. It does not
41 // emit unpopulated oneof fields or unpopulated extension fields.
42 // The JSON value emitted for unpopulated fields are as follows:
43 // ╔═══════╤════════════════════════════╗
44 // ║ JSON │ Protobuf field ║
45 // ╠═══════╪════════════════════════════╣
46 // ║ false │ proto3 boolean fields ║
47 // ║ 0 │ proto3 numeric fields ║
48 // ║ "" │ proto3 string/bytes fields ║
49 // ║ null │ proto2 scalar fields ║
50 // ║ null │ message fields ║
51 // ║ [] │ list fields ║
52 // ║ {} │ map fields ║
53 // ╚═══════╧════════════════════════════╝
54 EmitUnpopulated bool
55
Herbie Ong0b0f4032019-03-18 19:06:15 -070056 // If Indent is a non-empty string, it causes entries for an Array or Object
57 // to be preceded by the indent and trailed by a newline. Indent can only be
58 // composed of space or tab characters.
59 Indent string
60
Joe Tsai1c283042019-05-14 14:28:19 -070061 // Resolver is used for looking up types when expanding google.protobuf.Any
62 // messages. If nil, this defaults to using protoregistry.GlobalTypes.
63 Resolver interface {
Damien Neil95faac22019-06-19 10:03:37 -070064 protoregistry.ExtensionTypeResolver
Joe Tsai1c283042019-05-14 14:28:19 -070065 protoregistry.MessageTypeResolver
66 }
Herbie Ong7b828bc2019-02-08 19:56:24 -080067}
68
Herbie Ong0b0f4032019-03-18 19:06:15 -070069// Marshal marshals the given proto.Message in the JSON format using options in
70// MarshalOptions.
Herbie Ong7b828bc2019-02-08 19:56:24 -080071func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
Herbie Ong822de2d2019-03-27 13:16:23 -070072 var err error
73 o.encoder, err = json.NewEncoder(o.Indent)
Herbie Ong87608a72019-03-06 14:32:24 -080074 if err != nil {
75 return nil, err
76 }
Herbie Ong822de2d2019-03-27 13:16:23 -070077 if o.Resolver == nil {
78 o.Resolver = protoregistry.GlobalTypes
79 }
Herbie Ong87608a72019-03-06 14:32:24 -080080
Herbie Ong822de2d2019-03-27 13:16:23 -070081 err = o.marshalMessage(m.ProtoReflect())
Damien Neil8c86fc52019-06-19 09:28:29 -070082 if err != nil {
Herbie Ong7b828bc2019-02-08 19:56:24 -080083 return nil, err
84 }
Damien Neil8c86fc52019-06-19 09:28:29 -070085 if o.AllowPartial {
86 return o.encoder.Bytes(), nil
Damien Neil4686e232019-04-05 13:31:40 -070087 }
Damien Neil8c86fc52019-06-19 09:28:29 -070088 return o.encoder.Bytes(), proto.IsInitialized(m)
Herbie Ong87608a72019-03-06 14:32:24 -080089}
90
91// marshalMessage marshals the given protoreflect.Message.
Herbie Ong822de2d2019-03-27 13:16:23 -070092func (o MarshalOptions) marshalMessage(m pref.Message) error {
Joe Tsai0fc49f82019-05-01 12:29:25 -070093 if isCustomType(m.Descriptor().FullName()) {
Herbie Ong822de2d2019-03-27 13:16:23 -070094 return o.marshalCustomType(m)
Herbie Ong0b0f4032019-03-18 19:06:15 -070095 }
96
Herbie Ong822de2d2019-03-27 13:16:23 -070097 o.encoder.StartObject()
98 defer o.encoder.EndObject()
Damien Neil8c86fc52019-06-19 09:28:29 -070099 if err := o.marshalFields(m); err != nil {
Herbie Ong0b0f4032019-03-18 19:06:15 -0700100 return err
101 }
Herbie Ong87608a72019-03-06 14:32:24 -0800102
Damien Neil8c86fc52019-06-19 09:28:29 -0700103 return nil
Herbie Ong0b0f4032019-03-18 19:06:15 -0700104}
105
106// marshalFields marshals the fields in the given protoreflect.Message.
Herbie Ong822de2d2019-03-27 13:16:23 -0700107func (o MarshalOptions) marshalFields(m pref.Message) error {
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700108 messageDesc := m.Descriptor()
Joe Tsai1799d112019-08-08 13:31:59 -0700109 if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) {
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700110 return errors.New("no support for proto1 MessageSets")
111 }
112
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700113 // Marshal out known fields.
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700114 fieldDescs := messageDesc.Fields()
Herbie Ong87608a72019-03-06 14:32:24 -0800115 for i := 0; i < fieldDescs.Len(); i++ {
Herbie Ong7b828bc2019-02-08 19:56:24 -0800116 fd := fieldDescs.Get(i)
Herbie Ong984e5282019-09-06 00:29:48 -0700117 val := m.Get(fd)
Joe Tsai378c1322019-04-25 23:48:08 -0700118 if !m.Has(fd) {
Herbie Ong984e5282019-09-06 00:29:48 -0700119 if !o.EmitUnpopulated || fd.ContainingOneof() != nil {
120 continue
121 }
122 isProto2Scalar := fd.Syntax() == pref.Proto2 && fd.Default().IsValid()
123 isSingularMessage := fd.Cardinality() != pref.Repeated && fd.Message() != nil
124 if isProto2Scalar || isSingularMessage {
125 // Use invalid value to emit null.
126 val = pref.Value{}
127 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800128 }
129
Herbie Ong87608a72019-03-06 14:32:24 -0800130 name := fd.JSONName()
Damien Neil8c86fc52019-06-19 09:28:29 -0700131 if err := o.encoder.WriteName(name); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800132 return err
133 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700134 if err := o.marshalValue(val, fd); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800135 return err
Herbie Ong7b828bc2019-02-08 19:56:24 -0800136 }
137 }
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700138
139 // Marshal out extensions.
Damien Neil8c86fc52019-06-19 09:28:29 -0700140 if err := o.marshalExtensions(m); err != nil {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700141 return err
142 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700143 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800144}
145
Herbie Ong87608a72019-03-06 14:32:24 -0800146// marshalValue marshals the given protoreflect.Value.
Herbie Ong822de2d2019-03-27 13:16:23 -0700147func (o MarshalOptions) marshalValue(val pref.Value, fd pref.FieldDescriptor) error {
Joe Tsaiac31a352019-05-13 14:32:56 -0700148 switch {
149 case fd.IsList():
150 return o.marshalList(val.List(), fd)
151 case fd.IsMap():
152 return o.marshalMap(val.Map(), fd)
153 default:
154 return o.marshalSingular(val, fd)
Herbie Ong7b828bc2019-02-08 19:56:24 -0800155 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800156}
157
Herbie Ong87608a72019-03-06 14:32:24 -0800158// marshalSingular marshals the given non-repeated field value. This includes
159// all scalar types, enums, messages, and groups.
Herbie Ong822de2d2019-03-27 13:16:23 -0700160func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error {
Herbie Ong984e5282019-09-06 00:29:48 -0700161 if !val.IsValid() {
162 o.encoder.WriteNull()
163 return nil
164 }
165
Herbie Ong87608a72019-03-06 14:32:24 -0800166 switch kind := fd.Kind(); kind {
167 case pref.BoolKind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700168 o.encoder.WriteBool(val.Bool())
Herbie Ong87608a72019-03-06 14:32:24 -0800169
170 case pref.StringKind:
Damien Neil8c86fc52019-06-19 09:28:29 -0700171 if err := o.encoder.WriteString(val.String()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800172 return err
173 }
174
175 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700176 o.encoder.WriteInt(val.Int())
Herbie Ong87608a72019-03-06 14:32:24 -0800177
178 case pref.Uint32Kind, pref.Fixed32Kind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700179 o.encoder.WriteUint(val.Uint())
Herbie Ong7b828bc2019-02-08 19:56:24 -0800180
181 case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
182 pref.Sfixed64Kind, pref.Fixed64Kind:
Herbie Ong87608a72019-03-06 14:32:24 -0800183 // 64-bit integers are written out as JSON string.
Herbie Ong822de2d2019-03-27 13:16:23 -0700184 o.encoder.WriteString(val.String())
Herbie Ong7b828bc2019-02-08 19:56:24 -0800185
Herbie Ong87608a72019-03-06 14:32:24 -0800186 case pref.FloatKind:
187 // Encoder.WriteFloat handles the special numbers NaN and infinites.
Herbie Ong822de2d2019-03-27 13:16:23 -0700188 o.encoder.WriteFloat(val.Float(), 32)
Herbie Ong87608a72019-03-06 14:32:24 -0800189
190 case pref.DoubleKind:
191 // Encoder.WriteFloat handles the special numbers NaN and infinites.
Herbie Ong822de2d2019-03-27 13:16:23 -0700192 o.encoder.WriteFloat(val.Float(), 64)
Herbie Ong7b828bc2019-02-08 19:56:24 -0800193
194 case pref.BytesKind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700195 err := o.encoder.WriteString(base64.StdEncoding.EncodeToString(val.Bytes()))
Damien Neil8c86fc52019-06-19 09:28:29 -0700196 if err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800197 return err
198 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800199
200 case pref.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700201 if fd.Enum().FullName() == "google.protobuf.NullValue" {
Herbie Ong822de2d2019-03-27 13:16:23 -0700202 o.encoder.WriteNull()
Herbie Ong87608a72019-03-06 14:32:24 -0800203 } else {
Herbie Ong9111f3b2019-09-06 14:35:09 -0700204 desc := fd.Enum().Values().ByNumber(val.Enum())
205 if o.UseEnumNumbers || desc == nil {
206 o.encoder.WriteInt(int64(val.Enum()))
207 } else {
208 err := o.encoder.WriteString(string(desc.Name()))
209 if err != nil {
210 return err
211 }
212 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800213 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800214
215 case pref.MessageKind, pref.GroupKind:
Damien Neil8c86fc52019-06-19 09:28:29 -0700216 if err := o.marshalMessage(val.Message()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800217 return err
218 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800219
Herbie Ong87608a72019-03-06 14:32:24 -0800220 default:
Herbie Ong0b0f4032019-03-18 19:06:15 -0700221 panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind))
Herbie Ong87608a72019-03-06 14:32:24 -0800222 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700223 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800224}
225
Herbie Ong87608a72019-03-06 14:32:24 -0800226// marshalList marshals the given protoreflect.List.
Herbie Ong822de2d2019-03-27 13:16:23 -0700227func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) error {
228 o.encoder.StartArray()
229 defer o.encoder.EndArray()
Herbie Ong87608a72019-03-06 14:32:24 -0800230
Herbie Ong87608a72019-03-06 14:32:24 -0800231 for i := 0; i < list.Len(); i++ {
Herbie Ong7b828bc2019-02-08 19:56:24 -0800232 item := list.Get(i)
Damien Neil8c86fc52019-06-19 09:28:29 -0700233 if err := o.marshalSingular(item, fd); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800234 return err
Herbie Ong7b828bc2019-02-08 19:56:24 -0800235 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800236 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700237 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800238}
239
240type mapEntry struct {
241 key pref.MapKey
242 value pref.Value
243}
244
Herbie Ong87608a72019-03-06 14:32:24 -0800245// marshalMap marshals given protoreflect.Map.
Herbie Ong822de2d2019-03-27 13:16:23 -0700246func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) error {
247 o.encoder.StartObject()
248 defer o.encoder.EndObject()
Herbie Ong87608a72019-03-06 14:32:24 -0800249
Herbie Ong7b828bc2019-02-08 19:56:24 -0800250 // Get a sorted list based on keyType first.
251 entries := make([]mapEntry, 0, mmap.Len())
252 mmap.Range(func(key pref.MapKey, val pref.Value) bool {
253 entries = append(entries, mapEntry{key: key, value: val})
254 return true
255 })
Joe Tsaiac31a352019-05-13 14:32:56 -0700256 sortMap(fd.MapKey().Kind(), entries)
Herbie Ong7b828bc2019-02-08 19:56:24 -0800257
Herbie Ong87608a72019-03-06 14:32:24 -0800258 // Write out sorted list.
Herbie Ong7b828bc2019-02-08 19:56:24 -0800259 for _, entry := range entries {
Damien Neil8c86fc52019-06-19 09:28:29 -0700260 if err := o.encoder.WriteName(entry.key.String()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800261 return err
Herbie Ong7b828bc2019-02-08 19:56:24 -0800262 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700263 if err := o.marshalSingular(entry.value, fd.MapValue()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800264 return err
265 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800266 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700267 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800268}
269
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700270// sortMap orders list based on value of key field for deterministic ordering.
Herbie Ong7b828bc2019-02-08 19:56:24 -0800271func sortMap(keyKind pref.Kind, values []mapEntry) {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700272 sort.Slice(values, func(i, j int) bool {
273 switch keyKind {
274 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind,
275 pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
Herbie Ong7b828bc2019-02-08 19:56:24 -0800276 return values[i].key.Int() < values[j].key.Int()
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700277
278 case pref.Uint32Kind, pref.Fixed32Kind,
279 pref.Uint64Kind, pref.Fixed64Kind:
Herbie Ong7b828bc2019-02-08 19:56:24 -0800280 return values[i].key.Uint() < values[j].key.Uint()
281 }
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700282 return values[i].key.String() < values[j].key.String()
283 })
284}
285
286// marshalExtensions marshals extension fields.
Joe Tsai378c1322019-04-25 23:48:08 -0700287func (o MarshalOptions) marshalExtensions(m pref.Message) error {
288 type entry struct {
289 key string
290 value pref.Value
291 desc pref.FieldDescriptor
Herbie Ong7b828bc2019-02-08 19:56:24 -0800292 }
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700293
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700294 // Get a sorted list based on field key first.
Joe Tsai378c1322019-04-25 23:48:08 -0700295 var entries []entry
296 m.Range(func(fd pref.FieldDescriptor, v pref.Value) bool {
297 if !fd.IsExtension() {
298 return true
299 }
Joe Tsai378c1322019-04-25 23:48:08 -0700300
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700301 // For MessageSet extensions, the name used is the parent message.
Joe Tsaid4211502019-07-02 14:58:02 -0700302 name := fd.FullName()
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700303 if messageset.IsMessageSetExtension(fd) {
304 name = name.Parent()
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700305 }
306
Joe Tsai378c1322019-04-25 23:48:08 -0700307 // Use [name] format for JSON field name.
308 entries = append(entries, entry{
309 key: string(name),
310 value: v,
311 desc: fd,
312 })
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700313 return true
314 })
315
316 // Sort extensions lexicographically.
317 sort.Slice(entries, func(i, j int) bool {
318 return entries[i].key < entries[j].key
319 })
320
321 // Write out sorted list.
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700322 for _, entry := range entries {
323 // JSON field name is the proto field name enclosed in [], similar to
324 // textproto. This is consistent with Go v1 lib. C++ lib v3.7.0 does not
325 // marshal out extension fields.
Damien Neil8c86fc52019-06-19 09:28:29 -0700326 if err := o.encoder.WriteName("[" + entry.key + "]"); err != nil {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700327 return err
328 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700329 if err := o.marshalValue(entry.value, entry.desc); err != nil {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700330 return err
331 }
332 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700333 return nil
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700334}