github.com/webx-top/com@v1.2.12/json.go (about) 1 package com 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 8 "github.com/webx-top/com/encoding/json" 9 ) 10 11 // GetJSON Read json data, writes in struct f 12 func GetJSON(dat *string, s interface{}) error { 13 return json.Unmarshal([]byte(*dat), s) 14 } 15 16 // UnmarshalStream . 17 func UnmarshalStream(r io.Reader, m interface{}, fn func()) error { 18 dec := json.NewDecoder(r) 19 for { 20 if err := dec.Decode(m); err != nil { 21 if err == io.EOF { 22 break 23 } 24 return err 25 } 26 fn() 27 } 28 return nil 29 } 30 31 // MarshalStream . 32 func MarshalStream(w io.Writer, m interface{}) error { 33 enc := json.NewEncoder(w) 34 return enc.Encode(m) 35 } 36 37 // SetJSON Struct s will be converted to json format 38 func SetJSON(s interface{}) (string, error) { 39 dat, err := json.Marshal(s) 40 return string(dat), err 41 } 42 43 // ReadJSON Json data read from the specified file 44 func ReadJSON(path string, s interface{}) error { 45 dat, err1 := os.ReadFile(path) 46 if err1 != nil { 47 return err1 48 } 49 return json.Unmarshal(dat, s) 50 } 51 52 // WriteJSON The json data is written to the specified file 53 func WriteJSON(path string, dat *string) error { 54 _, err0 := os.Stat(path) 55 if err0 != nil || !os.IsExist(err0) { 56 os.Create(path) 57 } 58 return os.WriteFile(path, []byte(*dat), 0644) 59 } 60 61 // Dump 输出对象和数组的结构信息 62 func Dump(m interface{}, args ...bool) (r string) { 63 v, err := json.MarshalIndent(m, "", " ") 64 if err != nil { 65 fmt.Printf("%v\n", err) 66 } 67 r = string(v) 68 l := len(args) 69 if l < 1 || args[0] { 70 fmt.Println(r) 71 } 72 return 73 }