vitess.io/vitess@v0.16.2/go/cmd/vtctldclient/cli/json.go (about)

     1  /*
     2  Copyright 2021 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cli
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  
    23  	"google.golang.org/protobuf/encoding/protojson"
    24  
    25  	"google.golang.org/protobuf/proto"
    26  )
    27  
    28  // MarshalJSON marshals obj to a JSON string. It uses the jsonpb marshaler for
    29  // proto.Message types, with some sensible defaults, and falls back to the
    30  // standard Go marshaler otherwise. In both cases, the marshaled JSON is
    31  // indented with two spaces for readability.
    32  //
    33  // Unfortunately jsonpb only works for types that implement proto.Message,
    34  // either by being a proto message type or by anonymously embedding one, so for
    35  // other types that may have nested struct fields, we still use the standard Go
    36  // marshaler, which will result in different formattings.
    37  func MarshalJSON(obj any) ([]byte, error) {
    38  	switch obj := obj.(type) {
    39  	case proto.Message:
    40  		m := protojson.MarshalOptions{
    41  			Multiline:       true,
    42  			Indent:          "  ",
    43  			UseEnumNumbers:  true,
    44  			UseProtoNames:   true,
    45  			EmitUnpopulated: true,
    46  		}
    47  		return m.Marshal(obj)
    48  	default:
    49  		data, err := json.MarshalIndent(obj, "", "  ")
    50  		if err != nil {
    51  			return nil, fmt.Errorf("json.Marshal = %v", err)
    52  		}
    53  
    54  		return data, nil
    55  	}
    56  }