提交 f59e41f0 编写于 作者: martianzhang's avatar martianzhang

add JSONFind for json recursive find by key

上级 817e8dd4
......@@ -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
})
}
......@@ -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())
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册