mirror of https://github.com/tidwall/gjson.git
add set function
Change-Id: Ib15c9585f0083805a06fb709f12d65620618cf51
This commit is contained in:
parent
f92dbfc6b2
commit
af8364e2b8
38
gjson.go
38
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)
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue