From f59e41f0a2d4a640c753bdb63cb60548cfbfdf9d Mon Sep 17 00:00:00 2001 From: Leon Zhang Date: Tue, 8 Jan 2019 13:01:08 +0800 Subject: [PATCH] add JSONFind for json recursive find by key --- common/testdata/TestJSONFind.golden | 1 + common/tricks.go | 15 +++++++++++++ common/tricks_test.go | 33 +++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 common/testdata/TestJSONFind.golden diff --git a/common/testdata/TestJSONFind.golden b/common/testdata/TestJSONFind.golden new file mode 100644 index 0000000..0139cb6 --- /dev/null +++ b/common/testdata/TestJSONFind.golden @@ -0,0 +1 @@ +[Janet Elliotte Jason] diff --git a/common/tricks.go b/common/tricks.go index 53360ca..f3ff0b3 100644 --- a/common/tricks.go +++ b/common/tricks.go @@ -25,6 +25,8 @@ import ( "path/filepath" "reflect" "sort" + + "github.com/tidwall/gjson" ) // GoldenDiff 从 gofmt 学来的测试方法 @@ -104,3 +106,16 @@ func SortedKey(m interface{}) []string { sort.Strings(keys) return keys } + +// JSONFind iterate find name in json +func JSONFind(json string, name string, result *[]string) { + res := gjson.Parse(json) + res.ForEach(func(key, value gjson.Result) bool { + if key.String() == name { + *result = append(*result, value.String()) + } else { + JSONFind(value.String(), name, result) + } + return true // keep iterating + }) +} diff --git a/common/tricks_test.go b/common/tricks_test.go index 063750e..0d46e27 100644 --- a/common/tricks_test.go +++ b/common/tricks_test.go @@ -24,6 +24,7 @@ import ( ) func TestCaptureOutput(t *testing.T) { + Log.Debug("Entering function: %s", GetFunctionName()) c1 := make(chan string, 1) // test output buf large than 65535 length := 1<<16 + 1 @@ -48,4 +49,36 @@ func TestCaptureOutput(t *testing.T) { case <-time.After(1 * time.Second): t.Error("capture timeout, pipe read hangup") } + Log.Debug("Exiting function: %s", GetFunctionName()) +} + +func TestJSONFind(t *testing.T) { + Log.Debug("Entering function: %s", GetFunctionName()) + jsons := []string{ + `{ + "programmers": [ + { + "firstName": "Janet", + "lastName": "McLaughlin", + }, { + "firstName": "Elliotte", + "lastName": "Hunter", + }, { + "firstName": "Jason", + "lastName": "Harold", + } + ] +}`, + } + err := GoldenDiff(func() { + for _, json := range jsons { + var result []string + JSONFind(json, "firstName", &result) + fmt.Println(result) + } + }, t.Name(), update) + if err != nil { + t.Error(err) + } + Log.Debug("Exiting function: %s", GetFunctionName()) } -- GitLab