From 03e100b4a5f5e8ee646f52eb3a61cd074fe5d39f Mon Sep 17 00:00:00 2001 From: John Date: Fri, 26 Jan 2018 17:42:14 +0800 Subject: [PATCH] =?UTF-8?q?gparse=E6=96=B0=E5=A2=9ERemove=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E5=8F=96=E6=B6=88=E9=80=9A=E8=BF=87Set+nil?= =?UTF-8?q?=E6=9D=A5=E5=88=A0=E9=99=A4=E5=8F=98=E9=87=8F=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- g/encoding/gjson/gjson.go | 15 ++++++++++++--- g/encoding/gparser/gparser.go | 5 +++++ geg/encoding/gparser.go | 15 +++++++++++++-- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/g/encoding/gjson/gjson.go b/g/encoding/gjson/gjson.go index ab23acb02..aa4ced6cb 100644 --- a/g/encoding/gjson/gjson.go +++ b/g/encoding/gjson/gjson.go @@ -187,12 +187,22 @@ func (j *Json) GetFloat64(pattern string) float64 { return gconv.Float64(j.Get(pattern)) } +// 动态设置层级变量 +func (j *Json) Set(pattern string, value interface{}) error { + return j.setValue(pattern, value, false) +} + +// 动态删除层级变量 +func (j *Json) Remove(pattern string) error { + return j.setValue(pattern, nil, true) +} + // 根据pattern查找并设置数据 // 注意: // 1、写入的时候"."符号只能表示层级,不能使用带"."符号的键名; -// 2、写入的value为nil时,表示删除; +// 2、写入的value为nil且removed为true时,表示删除; // 3、里面的层级处理比较复杂,逻辑较复杂的地方在于层级检索及节点创建,叶子赋值; -func (j *Json) Set(pattern string, value interface{}) error { +func (j *Json) setValue(pattern string, value interface{}, removed bool) error { // 初始化判断 if *j.p == nil { if isNumeric(pattern) { @@ -206,7 +216,6 @@ func (j *Json) Set(pattern string, value interface{}) error { pointer = j.p pparent = nil - removed := false value = j.convertValue(value) array := strings.Split(pattern, ".") length := len(array) diff --git a/g/encoding/gparser/gparser.go b/g/encoding/gparser/gparser.go index 988f37e4b..3fee6ea10 100644 --- a/g/encoding/gparser/gparser.go +++ b/g/encoding/gparser/gparser.go @@ -89,6 +89,11 @@ func (p *Parser) Set(pattern string, value interface{}) error { return p.json.Set(pattern, value) } +// 动态删除变量节点 +func (p *Parser) Remove(pattern string) error { + return p.json.Remove(pattern) +} + // 根据约定字符串方式访问json解析数据,参数形如: "items.name.first", "list.0" // 返回的结果类型的interface{},因此需要自己做类型转换 // 如果找不到对应节点的数据,返回nil diff --git a/geg/encoding/gparser.go b/geg/encoding/gparser.go index d96a5fcd2..1f1fb7263 100644 --- a/geg/encoding/gparser.go +++ b/geg/encoding/gparser.go @@ -186,7 +186,18 @@ func convert() { } +func remove1() { + p := gparser.New(map[string]string{ + "k1" : "v1", + "k2" : "v2", + }) + p.Set("0.0.0.0.0.0.0.0", []int{1,2,3}) + p.Remove("0.0") + c, _ := p.ToJson() + fmt.Println(string(c)) +} + + func main() { - makeJson2() - //makeJson3() + remove1() } \ No newline at end of file