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

261 lines · 5284 bytes

  1// Package gson A tiny JSON lib to read and alter a JSON value.
  2package gson
  3
  4import (
  5	"bytes"
  6	"encoding/json"
  7	"fmt"
  8	"reflect"
  9	"regexp"
 10	"strconv"
 11	"strings"
 12	"sync"
 13)
 14
 15// JSON represent a JSON value
 16type JSON struct {
 17	lock  *sync.Mutex
 18	value *interface{}
 19}
 20
 21// MarshalJSON interface
 22func (j JSON) MarshalJSON() ([]byte, error) {
 23	return json.Marshal(j.Val())
 24}
 25
 26// Unmarshal is the same as [json.Unmarshal] for the underlying raw value.
 27// It should be called before other operations.
 28func (j JSON) Unmarshal(v interface{}) error {
 29	if j.value == nil {
 30		return fmt.Errorf("gson: no value to unmarshal")
 31	}
 32
 33	j.lock.Lock()
 34	defer j.lock.Unlock()
 35
 36	b, ok := (*j.value).([]byte)
 37	if !ok {
 38		return fmt.Errorf("gson: value has been parsed")
 39	}
 40
 41	return json.Unmarshal(b, v)
 42}
 43
 44// JSON string
 45func (j JSON) JSON(prefix, indent string) string {
 46	buf := bytes.NewBuffer(nil)
 47	enc := json.NewEncoder(buf)
 48	enc.SetEscapeHTML(false)
 49	enc.SetIndent(prefix, indent)
 50	_ = enc.Encode(j.Val())
 51	s := buf.String()
 52	return s[:len(s)-1]
 53}
 54
 55// Raw underlying value
 56func (j JSON) Raw() interface{} {
 57	if j.value == nil {
 58		return nil
 59	}
 60	return *j.value
 61}
 62
 63// String implements [fmt.Stringer] interface
 64func (j JSON) String() string {
 65	return fmt.Sprintf("%v", j.Val())
 66}
 67
 68// Get by json path. It's a shortcut for Gets.
 69func (j JSON) Get(path string) JSON {
 70	j, _ = j.Gets(Path(path)...)
 71	return j
 72}
 73
 74// Has an element is found on the path
 75func (j JSON) Has(path string) bool {
 76	_, has := j.Gets(Path(path)...)
 77	return has
 78}
 79
 80// Query section
 81type Query func(interface{}) (val interface{}, has bool)
 82
 83// Gets element by path sections. If a section is not string, int, or func, it will be ignored.
 84// If it's a func, the value will be passed to it, the result of it will the next level.
 85// The last return value will be false if not found.
 86func (j JSON) Gets(sections ...interface{}) (JSON, bool) {
 87	for _, sect := range sections {
 88		var val interface{}
 89		var has bool
 90
 91		if fn, ok := sect.(Query); ok {
 92			val, has = fn(j.Val())
 93		} else {
 94			val, has = get(reflect.ValueOf(j.Val()), sect)
 95		}
 96
 97		if !has {
 98			return New(nil), false
 99		}
100		j.value = &val
101	}
102	return j, true
103}
104
105func get(objVal reflect.Value, sect interface{}) (val interface{}, has bool) {
106	switch k := sect.(type) {
107	case int:
108		if objVal.Kind() != reflect.Slice || k >= objVal.Len() {
109			return
110		}
111
112		has = true
113		val = objVal.Index(k).Interface()
114
115	default:
116		sectVal := reflect.ValueOf(sect)
117
118		if objVal.Kind() != reflect.Map || !sectVal.Type().AssignableTo(objVal.Type().Key()) {
119			return
120		}
121
122		v := objVal.MapIndex(sectVal)
123		if !v.IsValid() {
124			return
125		}
126
127		has = true
128		val = v.Interface()
129	}
130
131	return
132}
133
134// Str value
135func (j JSON) Str() string {
136	v := j.Val()
137	if v, ok := v.(string); ok {
138		return v
139	}
140	return fmt.Sprintf("%v", v)
141}
142
143var floatType = reflect.TypeOf(.0)
144
145// Num value
146// returns zero value for type if underlying JSON type is not convertible.
147func (j JSON) Num() float64 {
148	v := reflect.ValueOf(j.Val())
149	if v.IsValid() && v.Type().ConvertibleTo(floatType) {
150		return v.Convert(floatType).Float()
151	}
152	return 0
153}
154
155// Bool value
156// returns zero value for type if underlying JSON type is not boolean
157func (j JSON) Bool() bool {
158	if v, ok := j.Val().(bool); ok {
159		return v
160	}
161	return false
162}
163
164// Nil or not
165func (j JSON) Nil() bool {
166	return j.Val() == nil
167}
168
169var intType = reflect.TypeOf(0)
170
171// Int value
172// returns zero value for type if underlying JSON type is not convertible.
173func (j JSON) Int() int {
174	v := reflect.ValueOf(j.Val())
175	if v.IsValid() && v.Type().ConvertibleTo(intType) {
176		return int(v.Convert(intType).Int())
177	}
178	return 0
179}
180
181// Map of JSON
182// returns empty map if underlying JSON object is not a map.
183func (j JSON) Map() map[string]JSON {
184	val := reflect.ValueOf(j.Val())
185	if val.IsValid() && val.Kind() == reflect.Map && val.Type().Key().Kind() == reflect.String {
186		obj := map[string]JSON{}
187		iter := val.MapRange()
188		for iter.Next() {
189			obj[iter.Key().String()] = New(iter.Value().Interface())
190		}
191		return obj
192	}
193
194	return make(map[string]JSON)
195}
196
197// Arr of JSON
198// returns empty array if underlying JSON is not an array.
199func (j JSON) Arr() []JSON {
200	val := reflect.ValueOf(j.Val())
201	if val.IsValid() && val.Kind() == reflect.Slice {
202		obj := []JSON{}
203		l := val.Len()
204		for i := 0; i < l; i++ {
205			obj = append(obj, New(val.Index(i).Interface()))
206		}
207		return obj
208	}
209
210	return make([]JSON, 0)
211}
212
213// Join elements
214func (j JSON) Join(sep string) string {
215	list := []string{}
216
217	for _, el := range j.Arr() {
218		list = append(list, el.Str())
219	}
220
221	return strings.Join(list, sep)
222}
223
224var regIndex = regexp.MustCompile(`^0|([1-9]\d*)$`)
225
226// Path from string
227func Path(path string) []interface{} {
228	list := strings.Split(path, ".")
229	sects := make([]interface{}, len(list))
230	for i, s := range list {
231		if regIndex.MatchString(s) {
232			index, err := strconv.ParseInt(s, 10, 64)
233			if err == nil {
234				sects[i] = int(index)
235				continue
236			}
237		}
238		sects[i] = s
239	}
240	return sects
241}
242
243// Num returns the pointer of the v
244func Num(v float64) *float64 {
245	return &v
246}
247
248// Int returns the pointer of the v
249func Int(v int) *int {
250	return &v
251}
252
253// Str returns the pointer of the v
254func Str(v string) *string {
255	return &v
256}
257
258// Bool returns the pointer of the v
259func Bool(v bool) *bool {
260	return &v
261}