github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/ioutil/json.go (about)

     1  // Copyright 2016 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package ioutil
     6  
     7  import (
     8  	"encoding/json"
     9  	"path/filepath"
    10  
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // TODO: Support unknown fields (probably by using go-codec's JSON
    15  // serializer/deserializer).
    16  
    17  // SerializeToJSONFile serializes the given object as JSON and writes
    18  // it to the given file, making its parent directory first if
    19  // necessary.
    20  func SerializeToJSONFile(obj interface{}, path string) error {
    21  	err := MkdirAll(filepath.Dir(path), 0700)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	buf, err := json.Marshal(obj)
    27  	if err != nil {
    28  		return errors.Wrapf(err, "failed to marshal %q as JSON", path)
    29  	}
    30  
    31  	return WriteFile(path, buf, 0600)
    32  }
    33  
    34  // DeserializeFromJSONFile deserializes the given JSON file into the
    35  // object pointed to by objPtr. It may return an error for which
    36  // ioutil.IsNotExist() returns true.
    37  func DeserializeFromJSONFile(path string, objPtr interface{}) error {
    38  	data, err := ReadFile(path)
    39  	if err != nil {
    40  		return err
    41  	}
    42  
    43  	err = json.Unmarshal(data, objPtr)
    44  	if err != nil {
    45  		return errors.Wrapf(err, "failed to unmarshal %q as JSON", path)
    46  	}
    47  
    48  	return nil
    49  }