vendor/github.com/ysmood/gson/write.go

175 lines · 3436 bytes

  1package gson
  2
  3import (
  4	"encoding/json"
  5	"io"
  6	"reflect"
  7	"sync"
  8)
  9
 10// New JSON from []byte, [io.Reader], or raw value.
 11func New(v interface{}) JSON {
 12	return JSON{&sync.Mutex{}, &v}
 13}
 14
 15// NewFrom json encoded string
 16func NewFrom(s string) JSON {
 17	return New([]byte(s))
 18}
 19
 20// UnmarshalJSON interface
 21func (j *JSON) UnmarshalJSON(b []byte) error {
 22	*j = New(b)
 23	return nil
 24}
 25
 26// Val of the underlying json value.
 27// The first time it's called, it will try to parse the underlying data.
 28func (j JSON) Val() interface{} {
 29	if j.value == nil {
 30		return nil
 31	}
 32
 33	j.lock.Lock()
 34	defer j.lock.Unlock()
 35
 36	for {
 37		val, ok := (*j.value).(JSON)
 38		if ok {
 39			*j.value = *val.value
 40		} else {
 41			break
 42		}
 43	}
 44
 45	var val interface{}
 46	switch v := (*j.value).(type) {
 47	case []byte:
 48		_ = json.Unmarshal(v, &val)
 49		*j.value = val
 50	case io.Reader:
 51		_ = json.NewDecoder(v).Decode(&val)
 52		*j.value = val
 53	}
 54
 55	return *j.value
 56}
 57
 58// Set by json path. It's a shortcut for Sets.
 59func (j *JSON) Set(path string, val interface{}) *JSON {
 60	return j.Sets(val, Path(path)...)
 61}
 62
 63var _map map[string]interface{}
 64var interfaceType = reflect.TypeOf(_map).Elem()
 65
 66// Sets element by path sections. If a section is not string or int, it will be ignored.
 67func (j *JSON) Sets(target interface{}, sections ...interface{}) *JSON {
 68	if j.value == nil {
 69		*j = New(nil)
 70	}
 71
 72	last := len(sections) - 1
 73	val := reflect.ValueOf(j.Val())
 74	override := func(v reflect.Value) {
 75		*j.value = v.Interface()
 76	}
 77
 78	if last == -1 {
 79		*j.value = target
 80		return j
 81	}
 82
 83	for i, s := range sections {
 84		sect := reflect.ValueOf(s)
 85		if val.Kind() == reflect.Interface {
 86			val = val.Elem()
 87		}
 88
 89		switch sect.Kind() {
 90		case reflect.Int:
 91			k := int(sect.Int())
 92			if val.Kind() != reflect.Slice || val.Len() <= k {
 93				nArr := reflect.ValueOf(make([]interface{}, k+1))
 94				if val.Kind() == reflect.Slice {
 95					reflect.Copy(nArr, val)
 96				}
 97				val = nArr
 98				override(val)
 99			}
100			if i == last {
101				val.Index(k).Set(reflect.ValueOf(target))
102				return j
103			}
104			prev := val
105			val = val.Index(k)
106			override = func(v reflect.Value) {
107				prev.Index(k).Set(v)
108			}
109		default:
110			targetVal := reflect.ValueOf(target)
111			if val.Kind() != reflect.Map {
112				val = reflect.MakeMap(reflect.MapOf(sect.Type(), interfaceType))
113				override(val)
114			}
115			if i == last {
116				val.SetMapIndex(sect, targetVal)
117			}
118			prev := val
119			val = val.MapIndex(sect)
120			override = func(v reflect.Value) {
121				prev.SetMapIndex(sect, v)
122			}
123		}
124	}
125	return j
126}
127
128// Del deletes the element at the path.
129func (j *JSON) Del(path string) *JSON {
130	j.Dels(Path(path)...)
131	return j
132}
133
134// Dels deletes the element at the path sections.
135// Return true if it's deleted.
136func (j *JSON) Dels(sections ...interface{}) bool {
137	l := len(sections)
138
139	if l == 0 {
140		j.value = nil
141		return true
142	}
143
144	last := sections[l-1]
145
146	parent, has := j.Gets(sections[:l-1]...)
147	if !has {
148		return false
149	}
150
151	parentVal := reflect.ValueOf(parent.Val())
152	lastVal := reflect.ValueOf(last)
153
154	switch k := last.(type) {
155	case int:
156		pl := parentVal.Len()
157		if parentVal.Kind() != reflect.Slice || k < 0 || k >= pl {
158			return false
159		}
160
161		j.Sets(reflect.AppendSlice(
162			parentVal.Slice(0, k),
163			parentVal.Slice(k+1, pl),
164		).Interface(), sections[:l-1]...)
165
166	default:
167		if parentVal.Kind() != reflect.Map || !lastVal.Type().AssignableTo(parentVal.Type().Key()) {
168			return false
169		}
170
171		parentVal.SetMapIndex(lastVal, reflect.Value{})
172	}
173
174	return true
175}