blob: c761fec5fb34448a91704e386d04f7c560934179 [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 Ong984e5282019-09-06 00:29:48 -070037 // EmitUnpopulated specifies whether to emit unpopulated fields. It does not
38 // emit unpopulated oneof fields or unpopulated extension fields.
39 // The JSON value emitted for unpopulated fields are as follows:
40 // ╔═══════╤════════════════════════════╗
41 // ║ JSON │ Protobuf field ║
42 // ╠═══════╪════════════════════════════╣
43 // ║ false │ proto3 boolean fields ║
44 // ║ 0 │ proto3 numeric fields ║
45 // ║ "" │ proto3 string/bytes fields ║
46 // ║ null │ proto2 scalar fields ║
47 // ║ null │ message fields ║
48 // ║ [] │ list fields ║
49 // ║ {} │ map fields ║
50 // ╚═══════╧════════════════════════════╝
51 EmitUnpopulated bool
52
Herbie Ong0b0f4032019-03-18 19:06:15 -070053 // If Indent is a non-empty string, it causes entries for an Array or Object
54 // to be preceded by the indent and trailed by a newline. Indent can only be
55 // composed of space or tab characters.
56 Indent string
57
Joe Tsai1c283042019-05-14 14:28:19 -070058 // Resolver is used for looking up types when expanding google.protobuf.Any
59 // messages. If nil, this defaults to using protoregistry.GlobalTypes.
60 Resolver interface {
Damien Neil95faac22019-06-19 10:03:37 -070061 protoregistry.ExtensionTypeResolver
Joe Tsai1c283042019-05-14 14:28:19 -070062 protoregistry.MessageTypeResolver
63 }
Herbie Ong7b828bc2019-02-08 19:56:24 -080064}
65
Herbie Ong0b0f4032019-03-18 19:06:15 -070066// Marshal marshals the given proto.Message in the JSON format using options in
67// MarshalOptions.
Herbie Ong7b828bc2019-02-08 19:56:24 -080068func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
Herbie Ong822de2d2019-03-27 13:16:23 -070069 var err error
70 o.encoder, err = json.NewEncoder(o.Indent)
Herbie Ong87608a72019-03-06 14:32:24 -080071 if err != nil {
72 return nil, err
73 }
Herbie Ong822de2d2019-03-27 13:16:23 -070074 if o.Resolver == nil {
75 o.Resolver = protoregistry.GlobalTypes
76 }
Herbie Ong87608a72019-03-06 14:32:24 -080077
Herbie Ong822de2d2019-03-27 13:16:23 -070078 err = o.marshalMessage(m.ProtoReflect())
Damien Neil8c86fc52019-06-19 09:28:29 -070079 if err != nil {
Herbie Ong7b828bc2019-02-08 19:56:24 -080080 return nil, err
81 }
Damien Neil8c86fc52019-06-19 09:28:29 -070082 if o.AllowPartial {
83 return o.encoder.Bytes(), nil
Damien Neil4686e232019-04-05 13:31:40 -070084 }
Damien Neil8c86fc52019-06-19 09:28:29 -070085 return o.encoder.Bytes(), proto.IsInitialized(m)
Herbie Ong87608a72019-03-06 14:32:24 -080086}
87
88// marshalMessage marshals the given protoreflect.Message.
Herbie Ong822de2d2019-03-27 13:16:23 -070089func (o MarshalOptions) marshalMessage(m pref.Message) error {
Joe Tsai0fc49f82019-05-01 12:29:25 -070090 if isCustomType(m.Descriptor().FullName()) {
Herbie Ong822de2d2019-03-27 13:16:23 -070091 return o.marshalCustomType(m)
Herbie Ong0b0f4032019-03-18 19:06:15 -070092 }
93
Herbie Ong822de2d2019-03-27 13:16:23 -070094 o.encoder.StartObject()
95 defer o.encoder.EndObject()
Damien Neil8c86fc52019-06-19 09:28:29 -070096 if err := o.marshalFields(m); err != nil {
Herbie Ong0b0f4032019-03-18 19:06:15 -070097 return err
98 }
Herbie Ong87608a72019-03-06 14:32:24 -080099
Damien Neil8c86fc52019-06-19 09:28:29 -0700100 return nil
Herbie Ong0b0f4032019-03-18 19:06:15 -0700101}
102
103// marshalFields marshals the fields in the given protoreflect.Message.
Herbie Ong822de2d2019-03-27 13:16:23 -0700104func (o MarshalOptions) marshalFields(m pref.Message) error {
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700105 messageDesc := m.Descriptor()
Joe Tsai1799d112019-08-08 13:31:59 -0700106 if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) {
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700107 return errors.New("no support for proto1 MessageSets")
108 }
109
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700110 // Marshal out known fields.
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700111 fieldDescs := messageDesc.Fields()
Herbie Ong87608a72019-03-06 14:32:24 -0800112 for i := 0; i < fieldDescs.Len(); i++ {
Herbie Ong7b828bc2019-02-08 19:56:24 -0800113 fd := fieldDescs.Get(i)
Herbie Ong984e5282019-09-06 00:29:48 -0700114 val := m.Get(fd)
Joe Tsai378c1322019-04-25 23:48:08 -0700115 if !m.Has(fd) {
Herbie Ong984e5282019-09-06 00:29:48 -0700116 if !o.EmitUnpopulated || fd.ContainingOneof() != nil {
117 continue
118 }
119 isProto2Scalar := fd.Syntax() == pref.Proto2 && fd.Default().IsValid()
120 isSingularMessage := fd.Cardinality() != pref.Repeated && fd.Message() != nil
121 if isProto2Scalar || isSingularMessage {
122 // Use invalid value to emit null.
123 val = pref.Value{}
124 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800125 }
126
Herbie Ong87608a72019-03-06 14:32:24 -0800127 name := fd.JSONName()
Damien Neil8c86fc52019-06-19 09:28:29 -0700128 if err := o.encoder.WriteName(name); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800129 return err
130 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700131 if err := o.marshalValue(val, fd); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800132 return err
Herbie Ong7b828bc2019-02-08 19:56:24 -0800133 }
134 }
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700135
136 // Marshal out extensions.
Damien Neil8c86fc52019-06-19 09:28:29 -0700137 if err := o.marshalExtensions(m); err != nil {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700138 return err
139 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700140 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800141}
142
Herbie Ong87608a72019-03-06 14:32:24 -0800143// marshalValue marshals the given protoreflect.Value.
Herbie Ong822de2d2019-03-27 13:16:23 -0700144func (o MarshalOptions) marshalValue(val pref.Value, fd pref.FieldDescriptor) error {
Joe Tsaiac31a352019-05-13 14:32:56 -0700145 switch {
146 case fd.IsList():
147 return o.marshalList(val.List(), fd)
148 case fd.IsMap():
149 return o.marshalMap(val.Map(), fd)
150 default:
151 return o.marshalSingular(val, fd)
Herbie Ong7b828bc2019-02-08 19:56:24 -0800152 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800153}
154
Herbie Ong87608a72019-03-06 14:32:24 -0800155// marshalSingular marshals the given non-repeated field value. This includes
156// all scalar types, enums, messages, and groups.
Herbie Ong822de2d2019-03-27 13:16:23 -0700157func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error {
Herbie Ong984e5282019-09-06 00:29:48 -0700158 if !val.IsValid() {
159 o.encoder.WriteNull()
160 return nil
161 }
162
Herbie Ong87608a72019-03-06 14:32:24 -0800163 switch kind := fd.Kind(); kind {
164 case pref.BoolKind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700165 o.encoder.WriteBool(val.Bool())
Herbie Ong87608a72019-03-06 14:32:24 -0800166
167 case pref.StringKind:
Damien Neil8c86fc52019-06-19 09:28:29 -0700168 if err := o.encoder.WriteString(val.String()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800169 return err
170 }
171
172 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700173 o.encoder.WriteInt(val.Int())
Herbie Ong87608a72019-03-06 14:32:24 -0800174
175 case pref.Uint32Kind, pref.Fixed32Kind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700176 o.encoder.WriteUint(val.Uint())
Herbie Ong7b828bc2019-02-08 19:56:24 -0800177
178 case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
179 pref.Sfixed64Kind, pref.Fixed64Kind:
Herbie Ong87608a72019-03-06 14:32:24 -0800180 // 64-bit integers are written out as JSON string.
Herbie Ong822de2d2019-03-27 13:16:23 -0700181 o.encoder.WriteString(val.String())
Herbie Ong7b828bc2019-02-08 19:56:24 -0800182
Herbie Ong87608a72019-03-06 14:32:24 -0800183 case pref.FloatKind:
184 // Encoder.WriteFloat handles the special numbers NaN and infinites.
Herbie Ong822de2d2019-03-27 13:16:23 -0700185 o.encoder.WriteFloat(val.Float(), 32)
Herbie Ong87608a72019-03-06 14:32:24 -0800186
187 case pref.DoubleKind:
188 // Encoder.WriteFloat handles the special numbers NaN and infinites.
Herbie Ong822de2d2019-03-27 13:16:23 -0700189 o.encoder.WriteFloat(val.Float(), 64)
Herbie Ong7b828bc2019-02-08 19:56:24 -0800190
191 case pref.BytesKind:
Herbie Ong822de2d2019-03-27 13:16:23 -0700192 err := o.encoder.WriteString(base64.StdEncoding.EncodeToString(val.Bytes()))
Damien Neil8c86fc52019-06-19 09:28:29 -0700193 if err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800194 return err
195 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800196
197 case pref.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700198 if fd.Enum().FullName() == "google.protobuf.NullValue" {
Herbie Ong822de2d2019-03-27 13:16:23 -0700199 o.encoder.WriteNull()
Joe Tsaid24bc722019-04-15 23:39:09 -0700200 } else if desc := fd.Enum().Values().ByNumber(val.Enum()); desc != nil {
Herbie Ong822de2d2019-03-27 13:16:23 -0700201 err := o.encoder.WriteString(string(desc.Name()))
Damien Neil8c86fc52019-06-19 09:28:29 -0700202 if err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800203 return err
204 }
205 } else {
206 // Use numeric value if there is no enum value descriptor.
Joe Tsaid24bc722019-04-15 23:39:09 -0700207 o.encoder.WriteInt(int64(val.Enum()))
Herbie Ong7b828bc2019-02-08 19:56:24 -0800208 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800209
210 case pref.MessageKind, pref.GroupKind:
Damien Neil8c86fc52019-06-19 09:28:29 -0700211 if err := o.marshalMessage(val.Message()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800212 return err
213 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800214
Herbie Ong87608a72019-03-06 14:32:24 -0800215 default:
Herbie Ong0b0f4032019-03-18 19:06:15 -0700216 panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind))
Herbie Ong87608a72019-03-06 14:32:24 -0800217 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700218 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800219}
220
Herbie Ong87608a72019-03-06 14:32:24 -0800221// marshalList marshals the given protoreflect.List.
Herbie Ong822de2d2019-03-27 13:16:23 -0700222func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) error {
223 o.encoder.StartArray()
224 defer o.encoder.EndArray()
Herbie Ong87608a72019-03-06 14:32:24 -0800225
Herbie Ong87608a72019-03-06 14:32:24 -0800226 for i := 0; i < list.Len(); i++ {
Herbie Ong7b828bc2019-02-08 19:56:24 -0800227 item := list.Get(i)
Damien Neil8c86fc52019-06-19 09:28:29 -0700228 if err := o.marshalSingular(item, fd); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800229 return err
Herbie Ong7b828bc2019-02-08 19:56:24 -0800230 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800231 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700232 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800233}
234
235type mapEntry struct {
236 key pref.MapKey
237 value pref.Value
238}
239
Herbie Ong87608a72019-03-06 14:32:24 -0800240// marshalMap marshals given protoreflect.Map.
Herbie Ong822de2d2019-03-27 13:16:23 -0700241func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) error {
242 o.encoder.StartObject()
243 defer o.encoder.EndObject()
Herbie Ong87608a72019-03-06 14:32:24 -0800244
Herbie Ong7b828bc2019-02-08 19:56:24 -0800245 // Get a sorted list based on keyType first.
246 entries := make([]mapEntry, 0, mmap.Len())
247 mmap.Range(func(key pref.MapKey, val pref.Value) bool {
248 entries = append(entries, mapEntry{key: key, value: val})
249 return true
250 })
Joe Tsaiac31a352019-05-13 14:32:56 -0700251 sortMap(fd.MapKey().Kind(), entries)
Herbie Ong7b828bc2019-02-08 19:56:24 -0800252
Herbie Ong87608a72019-03-06 14:32:24 -0800253 // Write out sorted list.
Herbie Ong7b828bc2019-02-08 19:56:24 -0800254 for _, entry := range entries {
Damien Neil8c86fc52019-06-19 09:28:29 -0700255 if err := o.encoder.WriteName(entry.key.String()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800256 return err
Herbie Ong7b828bc2019-02-08 19:56:24 -0800257 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700258 if err := o.marshalSingular(entry.value, fd.MapValue()); err != nil {
Herbie Ong87608a72019-03-06 14:32:24 -0800259 return err
260 }
Herbie Ong7b828bc2019-02-08 19:56:24 -0800261 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700262 return nil
Herbie Ong7b828bc2019-02-08 19:56:24 -0800263}
264
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700265// sortMap orders list based on value of key field for deterministic ordering.
Herbie Ong7b828bc2019-02-08 19:56:24 -0800266func sortMap(keyKind pref.Kind, values []mapEntry) {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700267 sort.Slice(values, func(i, j int) bool {
268 switch keyKind {
269 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind,
270 pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
Herbie Ong7b828bc2019-02-08 19:56:24 -0800271 return values[i].key.Int() < values[j].key.Int()
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700272
273 case pref.Uint32Kind, pref.Fixed32Kind,
274 pref.Uint64Kind, pref.Fixed64Kind:
Herbie Ong7b828bc2019-02-08 19:56:24 -0800275 return values[i].key.Uint() < values[j].key.Uint()
276 }
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700277 return values[i].key.String() < values[j].key.String()
278 })
279}
280
281// marshalExtensions marshals extension fields.
Joe Tsai378c1322019-04-25 23:48:08 -0700282func (o MarshalOptions) marshalExtensions(m pref.Message) error {
283 type entry struct {
284 key string
285 value pref.Value
286 desc pref.FieldDescriptor
Herbie Ong7b828bc2019-02-08 19:56:24 -0800287 }
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700288
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700289 // Get a sorted list based on field key first.
Joe Tsai378c1322019-04-25 23:48:08 -0700290 var entries []entry
291 m.Range(func(fd pref.FieldDescriptor, v pref.Value) bool {
292 if !fd.IsExtension() {
293 return true
294 }
Joe Tsai378c1322019-04-25 23:48:08 -0700295
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700296 // For MessageSet extensions, the name used is the parent message.
Joe Tsaid4211502019-07-02 14:58:02 -0700297 name := fd.FullName()
Joe Tsai5ae10aa2019-07-11 18:23:08 -0700298 if messageset.IsMessageSetExtension(fd) {
299 name = name.Parent()
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700300 }
301
Joe Tsai378c1322019-04-25 23:48:08 -0700302 // Use [name] format for JSON field name.
303 entries = append(entries, entry{
304 key: string(name),
305 value: v,
306 desc: fd,
307 })
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700308 return true
309 })
310
311 // Sort extensions lexicographically.
312 sort.Slice(entries, func(i, j int) bool {
313 return entries[i].key < entries[j].key
314 })
315
316 // Write out sorted list.
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700317 for _, entry := range entries {
318 // JSON field name is the proto field name enclosed in [], similar to
319 // textproto. This is consistent with Go v1 lib. C++ lib v3.7.0 does not
320 // marshal out extension fields.
Damien Neil8c86fc52019-06-19 09:28:29 -0700321 if err := o.encoder.WriteName("[" + entry.key + "]"); err != nil {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700322 return err
323 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700324 if err := o.marshalValue(entry.value, entry.desc); err != nil {
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700325 return err
326 }
327 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700328 return nil
Herbie Ongf83d5bb2019-03-14 00:01:27 -0700329}