github.com/richardwilkes/toolbox@v1.121.0/xio/fs/json.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package fs 11 12 import ( 13 "bufio" 14 "encoding/json" 15 "io" 16 "io/fs" 17 "os" 18 19 "github.com/richardwilkes/toolbox/errs" 20 "github.com/richardwilkes/toolbox/xio" 21 "github.com/richardwilkes/toolbox/xio/fs/safe" 22 ) 23 24 // LoadJSON data from the specified path. 25 func LoadJSON(path string, data any) error { 26 f, err := os.Open(path) 27 if err != nil { 28 return errs.NewWithCause(path, err) 29 } 30 return loadJSON(f, path, data) 31 } 32 33 // LoadJSONFromFS data from the specified filesystem path. 34 func LoadJSONFromFS(fsys fs.FS, path string, data any) error { 35 f, err := fsys.Open(path) 36 if err != nil { 37 return errs.NewWithCause(path, err) 38 } 39 return loadJSON(f, path, data) 40 } 41 42 func loadJSON(r io.ReadCloser, path string, data any) error { 43 defer xio.CloseIgnoringErrors(r) 44 if err := json.NewDecoder(bufio.NewReader(r)).Decode(data); err != nil { 45 return errs.NewWithCause(path, err) 46 } 47 return nil 48 } 49 50 // SaveJSON data to the specified path. 51 func SaveJSON(path string, data any, format bool) error { 52 return SaveJSONWithMode(path, data, format, 0o644) 53 } 54 55 // SaveJSONWithMode data to the specified path. 56 func SaveJSONWithMode(path string, data any, format bool, mode os.FileMode) error { 57 if err := safe.WriteFileWithMode(path, func(w io.Writer) error { 58 encoder := json.NewEncoder(w) 59 if format { 60 encoder.SetIndent("", " ") 61 } 62 return errs.Wrap(encoder.Encode(data)) 63 }, mode); err != nil { 64 return errs.NewWithCause(path, err) 65 } 66 return nil 67 }