From 9e8a6609fdffa82e4a58137d6ef69e9c5468ccec Mon Sep 17 00:00:00 2001 From: Inhere Date: Sun, 26 Mar 2023 10:51:45 +0800 Subject: [PATCH] :sparkles: feat(json,reflect): reflect add new util func for handle map data jsonutil: - WritePretty reflects: - EachMap - EachStrAnyMap --- jsonutil/jsonutil.go | 9 +++++++++ jsonutil/jsonutil_test.go | 6 ++++++ reflects/util.go | 21 +++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/jsonutil/jsonutil.go b/jsonutil/jsonutil.go index b1206b8ad..4efab13d0 100644 --- a/jsonutil/jsonutil.go +++ b/jsonutil/jsonutil.go @@ -20,6 +20,15 @@ func WriteFile(filePath string, data any) error { return os.WriteFile(filePath, jsonBytes, 0664) } +// WritePretty write pretty data to JSON file +func WritePretty(filePath string, data any) error { + bs, err := json.MarshalIndent(data, "", " ") + if err != nil { + return err + } + return os.WriteFile(filePath, bs, 0664) +} + // ReadFile Read JSON file data func ReadFile(filePath string, v any) error { file, err := os.Open(filePath) diff --git a/jsonutil/jsonutil_test.go b/jsonutil/jsonutil_test.go index faee9bb49..58c6e8988 100644 --- a/jsonutil/jsonutil_test.go +++ b/jsonutil/jsonutil_test.go @@ -95,6 +95,12 @@ func TestWriteReadFile(t *testing.T) { err := jsonutil.WriteFile("testdata/test.json", &user) assert.NoErr(t, err) + err = jsonutil.WritePretty("testdata/test2.json", &user) + assert.NoErr(t, err) + + // err = jsonutil.WritePretty("/path/to/not-exist.json", &user) + // assert.Err(t, err) + err = jsonutil.ReadFile("testdata/test.json", &user) assert.NoErr(t, err) diff --git a/reflects/util.go b/reflects/util.go index f8d294149..909ca5430 100644 --- a/reflects/util.go +++ b/reflects/util.go @@ -82,6 +82,27 @@ func SetValue(rv reflect.Value, val any) error { return err } +// EachMap process any map data +func EachMap(mp reflect.Value, fn func(key, val reflect.Value)) { + if fn == nil { + return + } + if mp.Kind() != reflect.Map { + panic("only allow map value data") + } + + for _, key := range mp.MapKeys() { + fn(key, mp.MapIndex(key)) + } +} + +// EachStrAnyMap process any map data as string key and any value +func EachStrAnyMap(mp reflect.Value, fn func(key string, val any)) { + EachMap(mp, func(key, val reflect.Value) { + fn(String(key), val.Interface()) + }) +} + // FlatFunc custom collect handle func type FlatFunc func(path string, val reflect.Value)