[TOC] # 安装 ~~~ go get -u github.com/tidwall/sjson ~~~ # 设置值 ~~~ import "github.com/tidwall/sjson" const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}` func main() { //把name.last的值给改变了 value, _ := sjson.Set(json, "name.last", "Anderson") println(value) } ~~~ 输出 ~~~ {"name":{"first":"Janet","last":"Anderson"},"age":47} ~~~ # 路径语法 路径是由点分隔的一系列键。点和冒号字符可以转义`\` ~~~ { "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "James", "last": "Murphy"}, {"first": "Roger", "last": "Craig"} ] } ~~~ ~~~ "name.last" >> "Anderson" "age" >> 37 "children.1" >> "Alex" "friends.1.last" >> "Craig" ~~~ 用`-1`键可用于将值附加到现有数组: ~~~ "children.-1" >> appends a new value to the end of the children array ~~~ 通常,数字键用于修改数组,但可以使用冒号字符强制数字对象键: ~~~ { "users":{ "2313":{"name":"Sara"}, "7839":{"name":"Andy"} } } ~~~ 冒号路径 ~~~ "users.:2313.name" >> "Sara" ~~~ # 支持的类型 ~~~ sjson.Set(`{"key":true}`, "key", nil) sjson.Set(`{"key":true}`, "key", false) sjson.Set(`{"key":true}`, "key", 1) sjson.Set(`{"key":true}`, "key", 10.5) sjson.Set(`{"key":true}`, "key", "hello") sjson.Set(`{"key":true}`, "key", map[string]interface{}{"hello":"world"}) ~~~ 输出 ~~~ {"key":null} {"key":false} {"key":1} {"key":10.5} {"key":"hello"} {"key":{"hello":"world"}} ~~~ 当一个类型无法识别时,SJSON将回退到`encoding/json`Marshaller # 从空文档设置一个值 ~~~ value, _ := sjson.Set("", "name", "Tom") println(value) // Output: // {"name":"Tom"} ~~~ # 从空文档设置嵌套值 ~~~ value, _ := sjson.Set("", "name.last", "Anderson") println(value) // Output: // {"name":{"last":"Anderson"}} ~~~ # 设置新值 ~~~ value, _ := sjson.Set(`{"name":{"last":"Anderson"}}`, "name.first", "Sara") println(value) // Output: // {"name":{"first":"Sara","last":"Anderson"}} ~~~ # 更新现有值 ~~~ value, _ := sjson.Set(`{"name":{"last":"Anderson"}}`, "name.last", "Smith") println(value) // Output: // {"name":{"last":"Smith"}} ~~~ # 设置一个新的数组值 ~~~ value, _ := sjson.Set(`{"friends":["Andy","Carol"]}`, "friends.2", "Sara") println(value) // Output: // {"friends":["Andy","Carol","Sara"] ~~~ # 使用`-1`路径中的键附加数组值 ~~~ value, _ := sjson.Set(`{"friends":["Andy","Carol"]}`, "friends.-1", "Sara") println(value) // Output: // {"friends":["Andy","Carol","Sara"] ~~~ # 附加一个超过结尾的数组值 ~~~ value, _ := sjson.Set(`{"friends":["Andy","Carol"]}`, "friends.4", "Sara") println(value) // Output: // {"friends":["Andy","Carol",null,null,"Sara"] ~~~ # 删除一个值 ~~~go value, _ := sjson.Delete(`{"name":{"first":"Sara","last":"Anderson"}}`, "name.first") println(value) // Output: // {"name":{"last":"Anderson"}} ~~~ # 删除一个数组值 ~~~ value, _ := sjson.Delete(`{"friends":["Andy","Carol"]}`, "friends.1") println(value) // Output: // {"friends":["Andy"]} ~~~ # 删除最后一个数组值 ~~~ value, _ := sjson.Delete(`{"friends":["Andy","Carol"]}`, "friends.-1") println(value) // Output: // {"friends":["Andy"]} ~~~