add set function

Change-Id: Ib15c9585f0083805a06fb709f12d65620618cf51
This commit is contained in:
chenqi.seven 2018-08-02 19:10:37 +08:00
parent f92dbfc6b2
commit af8364e2b8
2 changed files with 44 additions and 0 deletions

View File

@ -2102,3 +2102,41 @@ func floatToInt(f float64) (n int64, ok bool) {
}
return 0, false
}
func buildItem(paths []string, value interface{}) interface{} {
if len(paths) == 0 {
return value
}
resultMap := map[string]interface{}{}
resultMap[paths[0]] = buildItem(paths[1:], value)
return &resultMap
}
func updateItem(input Result, paths []string, value interface{}) interface{} {
if len(paths) == 0 {
return value
}
inputMap := input.Map()
nextResult := inputMap[paths[0]]
var result interface{}
if nextResult.Exists() {
result = updateItem(nextResult, paths[1:], value)
} else {
result = buildItem(paths[1:], value)
}
resultMap := map[string]interface{}{}
// build new map
for k, v := range inputMap {
resultMap[k] = v.Value()
}
resultMap[paths[0]] = result
return &resultMap
}
func Set(input string, path string, value interface{}) Result {
paths := strings.Split(path, ".")
result := Parse(input)
resultInterface := updateItem(result, paths, value)
data, _ := json.Marshal(resultInterface)
return ParseBytes(data)
}

View File

@ -1406,3 +1406,9 @@ func TestDuplicateKeys(t *testing.T) {
t.Fatal("should be valid")
}
}
func TestSet(t *testing.T) {
var json = `{"name": "Peter","data":{"address":"some where"}}`
result := Set(json, "data.address", "no where")
t.Logf("%v", result.String())
}