gitee.com/quant1x/gox@v1.7.6/fastjson/update.go (about) 1 package fastjson 2 3 import ( 4 "strconv" 5 "strings" 6 ) 7 8 // Del deletes the entry with the given key from o. 9 func (o *Object) Del(key string) { 10 if o == nil { 11 return 12 } 13 if !o.keysUnescaped && strings.IndexByte(key, '\\') < 0 { 14 // Fast path - try searching for the key without object keys unescaping. 15 for i, kv := range o.kvs { 16 if kv.k == key { 17 o.kvs = append(o.kvs[:i], o.kvs[i+1:]...) 18 return 19 } 20 } 21 } 22 23 // Slow path - unescape object keys before item search. 24 o.unescapeKeys() 25 26 for i, kv := range o.kvs { 27 if kv.k == key { 28 o.kvs = append(o.kvs[:i], o.kvs[i+1:]...) 29 return 30 } 31 } 32 } 33 34 // Del deletes the entry with the given key from array or object v. 35 func (v *Value) Del(key string) { 36 if v == nil { 37 return 38 } 39 if v.t == TypeObject { 40 v.o.Del(key) 41 return 42 } 43 if v.t == TypeArray { 44 n, err := strconv.Atoi(key) 45 if err != nil || n < 0 || n >= len(v.a) { 46 return 47 } 48 v.a = append(v.a[:n], v.a[n+1:]...) 49 } 50 } 51 52 // Set sets (key, value) entry in the o. 53 // 54 // The value must be unchanged during o lifetime. 55 func (o *Object) Set(key string, value *Value) { 56 if o == nil { 57 return 58 } 59 if value == nil { 60 value = valueNull 61 } 62 o.unescapeKeys() 63 64 // Try substituting already existing entry with the given key. 65 for i := range o.kvs { 66 kv := &o.kvs[i] 67 if kv.k == key { 68 kv.v = value 69 return 70 } 71 } 72 73 // Add new entry. 74 kv := o.getKV() 75 kv.k = key 76 kv.v = value 77 } 78 79 // Set sets (key, value) entry in the array or object v. 80 // 81 // The value must be unchanged during v lifetime. 82 func (v *Value) Set(key string, value *Value) { 83 if v == nil { 84 return 85 } 86 if v.t == TypeObject { 87 v.o.Set(key, value) 88 return 89 } 90 if v.t == TypeArray { 91 idx, err := strconv.Atoi(key) 92 if err != nil || idx < 0 { 93 return 94 } 95 v.SetArrayItem(idx, value) 96 } 97 } 98 99 // SetArrayItem sets the value in the array v at idx position. 100 // 101 // The value must be unchanged during v lifetime. 102 func (v *Value) SetArrayItem(idx int, value *Value) { 103 if v == nil || v.t != TypeArray { 104 return 105 } 106 for idx >= len(v.a) { 107 v.a = append(v.a, valueNull) 108 } 109 v.a[idx] = value 110 }