code.vegaprotocol.io/vega@v0.79.0/libs/json/json.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package json
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  )
    22  
    23  func Prettify(data interface{}) ([]byte, error) {
    24  	bytes, err := json.MarshalIndent(data, "  ", "  ")
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	return bytes, nil
    29  }
    30  
    31  func PrettifyStr(data interface{}) (string, error) {
    32  	bytes, err := Prettify(data)
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  	return string(bytes), nil
    37  }
    38  
    39  func PrettyPrint(data interface{}) error {
    40  	prettifiedData, err := PrettifyStr(data)
    41  	if err != nil {
    42  		return err
    43  	}
    44  	fmt.Println(prettifiedData)
    45  	return nil
    46  }
    47  
    48  func Print(data interface{}) error {
    49  	buf, err := json.Marshal(data)
    50  	if err != nil {
    51  		return fmt.Errorf("unable to marshal message: %w", err)
    52  	}
    53  
    54  	fmt.Printf("%v\n", string(buf))
    55  
    56  	return nil
    57  }