From af8364e2b88fe56782f9b9915dfddda34a5f4172 Mon Sep 17 00:00:00 2001 From: "chenqi.seven" Date: Thu, 2 Aug 2018 19:10:37 +0800 Subject: [PATCH] add set function Change-Id: Ib15c9585f0083805a06fb709f12d65620618cf51 --- gjson.go | 38 ++++++++++++++++++++++++++++++++++++++ gjson_test.go | 6 ++++++ 2 files changed, 44 insertions(+) diff --git a/gjson.go b/gjson.go index 1da1552..e1f5cf7 100644 --- a/gjson.go +++ b/gjson.go @@ -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) +} diff --git a/gjson_test.go b/gjson_test.go index 867fae6..3396721 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -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()) +}