gopkg.in/essentialkaos/ek.v3@v3.5.1/jsonutil/jsonutil.go (about) 1 // Package jsonutil provides methods for working with json data 2 package jsonutil 3 4 // ////////////////////////////////////////////////////////////////////////////////// // 5 // // 6 // Copyright (c) 2009-2016 Essential Kaos // 7 // Essential Kaos Open Source License <http://essentialkaos.com/ekol?en> // 8 // // 9 // ////////////////////////////////////////////////////////////////////////////////// // 10 11 import ( 12 "encoding/json" 13 "io/ioutil" 14 "os" 15 ) 16 17 // ////////////////////////////////////////////////////////////////////////////////// // 18 19 // DecodeFile reads and decode json file 20 func DecodeFile(file string, v interface{}) error { 21 data, err := ioutil.ReadFile(file) 22 23 if err != nil { 24 return err 25 } 26 27 return json.Unmarshal(data, v) 28 } 29 30 // EncodeToFile encode data to json and save to file 31 func EncodeToFile(file string, v interface{}) error { 32 fd, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY, 0644) 33 34 if err != nil { 35 return err 36 } 37 38 defer fd.Close() 39 40 jsonData, err := json.MarshalIndent(v, "", " ") 41 42 if err != nil { 43 return err 44 } 45 46 jsonData = append(jsonData, byte('\n')) 47 48 _, err = fd.Write(jsonData) 49 50 if err != nil { 51 return err 52 } 53 54 return nil 55 }