github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/utils/json.go (about)

     1  /*
     2  Copyright 2017 Mirantis
     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 utils
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"log"
    24  	"os"
    25  )
    26  
    27  // ToJSON converts the specified object to indented JSON.
    28  // It panics in case if the object connot be converted.
    29  func ToJSON(o interface{}) string {
    30  	bs, err := json.MarshalIndent(o, "", "  ")
    31  	if err != nil {
    32  		log.Panicf("error marshalling json: %v", err)
    33  	}
    34  	return string(bs)
    35  }
    36  
    37  // ToJSONUnindented converts the specified object to unindented JSON.
    38  // It panics in case if the object connot be converted.
    39  func ToJSONUnindented(o interface{}) string {
    40  	bs, err := json.Marshal(o)
    41  	if err != nil {
    42  		log.Panicf("error marshalling json: %v", err)
    43  	}
    44  	return string(bs)
    45  }
    46  
    47  // ReadJSON converts data from file specified by `filename` to provided as `v`
    48  // interface.
    49  func ReadJSON(filename string, v interface{}) error {
    50  	content, err := ioutil.ReadFile(filename)
    51  	if err != nil {
    52  		return fmt.Errorf("error reading json file %q: %v", filename, err)
    53  	}
    54  
    55  	if err := json.Unmarshal(content, v); err != nil {
    56  		return fmt.Errorf("failed to parse json file %q: %v", filename, err)
    57  	}
    58  
    59  	return nil
    60  }
    61  
    62  // WriteJSON saves under specified `filename` data provided in `v` interface
    63  // setting file mode according to `perm` value.
    64  func WriteJSON(filename string, v interface{}, perm os.FileMode) error {
    65  	content, err := json.Marshal(v)
    66  	if err != nil {
    67  		return fmt.Errorf("couldn't marshal the data to JSON for %q: %v", filename, err)
    68  	}
    69  	if err := ioutil.WriteFile(filename, content, perm); err != nil {
    70  		return fmt.Errorf("error writing JSON data file %q: %v", filename, err)
    71  	}
    72  	return nil
    73  }