map.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package json
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "reflect"
  7. "strconv"
  8. )
  9. // Map type
  10. type Map map[string]interface{}
  11. // New init Map object
  12. func NewMap() Map {
  13. return make(Map)
  14. }
  15. // FromInterface convert map[string]interface{} or Map interface to Map
  16. func MapFromInterface(iface interface{}) (res Map) {
  17. switch val := iface.(type) {
  18. case map[string]interface{}:
  19. res = FromMap(val)
  20. case Map:
  21. res = val
  22. default:
  23. res = NewMap()
  24. }
  25. return
  26. }
  27. // FromMap convert map[string]interface{} to Map object
  28. func FromMap(m map[string]interface{}) Map {
  29. return Map(m)
  30. }
  31. // Bool returns bool value by key
  32. func (s Map) Bool(key string, defaultVal bool) bool {
  33. if res, check := s[key].(bool); check {
  34. return res
  35. }
  36. return defaultVal
  37. }
  38. // KeyExists check value exists by key
  39. func (s Map) KeyExists(key string) bool {
  40. _, check := s[key]
  41. return check
  42. }
  43. // KeysExists check values exists by keys list.
  44. // Returns the first blank key found.
  45. // If all keys are defined, an empty string will be returned
  46. func (s Map) KeysExists(keys []string) string {
  47. for _, key := range keys {
  48. if _, check := s[key]; !check {
  49. return key
  50. }
  51. }
  52. return ""
  53. }
  54. func val(l, r interface{}) (res reflect.Value) {
  55. lVal, rVal := reflect.ValueOf(l), reflect.ValueOf(r)
  56. if lVal.Kind() == reflect.Ptr && rVal.Kind() != reflect.Ptr {
  57. return val(lVal.Elem().Interface(), r)
  58. }
  59. defer func() {
  60. if r := recover(); r != nil {
  61. res = rVal
  62. }
  63. }()
  64. res = lVal.Convert(rVal.Type())
  65. return
  66. }
  67. func isType(l, r any) bool {
  68. rType := reflect.ValueOf(r).Type()
  69. lType := reflect.ValueOf(l).Type()
  70. //log.Println(rType, lType, reflect.ValueOf(iface).Convert(rType))
  71. return lType.ConvertibleTo(rType)
  72. }
  73. func (s Map) IsInt(key string) bool {
  74. if iface, check := s[key]; check {
  75. return isType(iface, int(0))
  76. }
  77. return false
  78. }
  79. func (s Map) IsBoolean(key string) bool {
  80. if iface, check := s[key]; check {
  81. return isType(iface, false)
  82. }
  83. return false
  84. }
  85. // Int returns int64 value by key.
  86. // If key isn't defined will be returned defaultVal arg value
  87. func (s Map) Int(key string, defaultVal int64) int64 {
  88. if iface, check := s[key]; check {
  89. return val(iface, defaultVal).Int()
  90. }
  91. return defaultVal
  92. }
  93. func (s Map) Int32(key string, defaultVal int) int {
  94. if iface, check := s[key]; check {
  95. return val(iface, defaultVal).Interface().(int)
  96. }
  97. return defaultVal
  98. }
  99. // Value returns interface object with attempt to convert to defaultVal type.
  100. // If key isn't defined will be returned defaultVal arg value
  101. func (s Map) Value(key string, defaultVal interface{}) interface{} {
  102. // check value exists by key
  103. if iface, check := s[key]; check {
  104. // check defaultVal is valid
  105. dVal := reflect.ValueOf(defaultVal)
  106. if !dVal.IsValid() {
  107. // invalid, return arrived interface
  108. return iface
  109. }
  110. // defaultVal is valid, attempt to convert found value to defaultVal type
  111. lVal := reflect.ValueOf(iface)
  112. switch {
  113. case !lVal.IsValid():
  114. return defaultVal // invalid found value, return defaultVal
  115. case lVal.Kind() == dVal.Kind():
  116. return iface // types of found value and defaultVal is match. return found value
  117. case lVal.Type().ConvertibleTo(dVal.Type()):
  118. return lVal.Convert(dVal.Type()).Interface() // found value type can be converted to defaultVal type. return converted found value
  119. default:
  120. {
  121. // found value type can't be converted to defaultVal type. If found value is string, attempt to convert to number value
  122. if lVal.Kind() == reflect.String {
  123. switch dVal.Kind() {
  124. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  125. val, err := strconv.Atoi(lVal.String())
  126. if err != nil {
  127. return defaultVal
  128. }
  129. lVal = reflect.ValueOf(val)
  130. return lVal.Convert(dVal.Type())
  131. case reflect.Float32, reflect.Float64:
  132. val, err := strconv.ParseFloat(lVal.String(), 64)
  133. if err != nil {
  134. return defaultVal
  135. }
  136. lVal = reflect.ValueOf(val)
  137. return lVal.Convert(dVal.Type())
  138. }
  139. }
  140. }
  141. }
  142. }
  143. return defaultVal
  144. }
  145. // ValueJSON returns json source object by key
  146. // If key isn't defined will be returned defaultVal arg value
  147. func (s Map) ValueJSON(key string, defaultVal []byte) (res []byte) {
  148. res = defaultVal
  149. if s.KeyExists(key) {
  150. if r, err := json.Marshal(s[key]); err == nil {
  151. res = r
  152. }
  153. }
  154. return
  155. }
  156. // String returns string value by key
  157. // If key isn't defined will be returned defaultVal arg value
  158. func (s Map) String(key, defaultVal string) string {
  159. if iface, check := s[key]; check {
  160. return val(iface, defaultVal).String()
  161. }
  162. return defaultVal
  163. }
  164. func (s Map) EachSlice(key string, each func(int, any) bool) {
  165. sl := s.Slice(key, []any{})
  166. for i, val := range sl {
  167. if !each(i, val) {
  168. return
  169. }
  170. }
  171. }
  172. func (s Map) EachMap(key string, each func(int, Map) bool) {
  173. s.EachSlice(key, func(i int, val any) bool {
  174. switch val.(type) {
  175. case map[string]any:
  176. return each(i, Map(val.(map[string]any)))
  177. case Map:
  178. return each(i, val.(Map))
  179. default:
  180. return true
  181. }
  182. })
  183. }
  184. func (s Map) StringWithError(key, defaultVal string) (string, error) {
  185. if iface, check := s[key]; check {
  186. val := val(iface, defaultVal).String()
  187. if val == defaultVal {
  188. return defaultVal, fmt.Errorf("FIELD [%s] IS EMPTY", key)
  189. }
  190. return val, nil
  191. }
  192. return defaultVal, fmt.Errorf("FIELD [%s] IS NOT EXISTS", key)
  193. }
  194. func (s Map) Bytes(key string, defaultVal []byte) []byte {
  195. if iface, check := s[key]; check {
  196. return []byte(val(iface, defaultVal).String())
  197. }
  198. return defaultVal
  199. }
  200. func (s Map) BytesWithError(key string, defaultVal []byte) ([]byte, error) {
  201. if iface, check := s[key]; check {
  202. return []byte(val(iface, defaultVal).String()), nil
  203. }
  204. return defaultVal, fmt.Errorf("FIELD [%s] IS NOT EXISTS", key)
  205. }
  206. func (s Map) StringVal(key, defaultVal string) string {
  207. if iface, check := s[key]; check {
  208. return fmt.Sprint(iface)
  209. }
  210. return defaultVal
  211. }
  212. // Slce returns slice of interface{} by key
  213. // If key isn't defined or have a different type will be returned defaultVal arg value
  214. func (s Map) Slice(key string, defaultVal []interface{}) (res []interface{}) {
  215. if arr, check := s[key].([]interface{}); check {
  216. res = arr
  217. } else {
  218. res = defaultVal
  219. }
  220. return
  221. }
  222. // StringSlice returns string slice by key
  223. // If key isn't defined will be returned defaultVal arg value
  224. func (s Map) StringSlice(key string, defaultVal []string) (res []string) {
  225. if arr, check := s[key].([]interface{}); check {
  226. res = make([]string, len(arr))
  227. for i, v := range arr {
  228. res[i] = fmt.Sprint(v)
  229. }
  230. } else {
  231. res = defaultVal
  232. }
  233. return
  234. }
  235. // Map returns Map object by key
  236. // If key isn't defined or have other type will be returned defaultVal arg value
  237. func (s Map) Map(key string, defaultVal Map) (res Map) {
  238. val := s[key]
  239. switch iface := val.(type) {
  240. case Map:
  241. res = iface
  242. case map[string]interface{}:
  243. res = Map(iface)
  244. default:
  245. res = defaultVal
  246. }
  247. return
  248. }
  249. // JSON returns JSON source of the self object
  250. func (s Map) JSON() (res []byte) {
  251. res, _ = json.Marshal(s)
  252. return
  253. }
  254. // JSONIndent returns JSON source of the self object with indent
  255. func (s Map) JSONIndent(prefix, indent string) (res []byte) {
  256. res, _ = json.MarshalIndent(s, prefix, indent)
  257. return
  258. }
  259. func (s Map) JSONString() (res string) {
  260. if data, err := json.Marshal(s); err == nil {
  261. res = string(data)
  262. }
  263. return
  264. }
  265. func (s Map) JSONPrettyString() (res string) {
  266. if data, err := json.MarshalIndent(s, "", "\t"); err == nil {
  267. res = string(data)
  268. }
  269. return
  270. }
  271. func (s Map) LogPretty() {
  272. log.Println(s.JSONPrettyString())
  273. }
  274. // ToMap returns map[string]interface{} of the self object
  275. func (s Map) ToMap() map[string]interface{} { return map[string]interface{}(s) }
  276. // Copy returns copied map (todo dipcopy)
  277. func (s Map) Copy() (res Map) {
  278. res = make(Map)
  279. for key, val := range s {
  280. res[key] = val
  281. }
  282. return
  283. }
  284. func (s Map) IsEmpty() bool {
  285. return len(s) == 0
  286. }
  287. func (s Map) Update(m Map) {
  288. for key, val := range m {
  289. s[key] = val
  290. }
  291. }
  292. func (s Map) StorePtr(key string, val interface{}) interface{} {
  293. s[key] = &val
  294. return &val
  295. }
  296. func (s Map) Variable(key string, ptr interface{}) bool {
  297. val, check := s[key]
  298. if !check {
  299. // value is not exists
  300. return false
  301. }
  302. vVal := reflect.ValueOf(ptr)
  303. if vVal.Kind() != reflect.Ptr {
  304. // ptr is not a pointer
  305. return false
  306. }
  307. vElem := vVal.Elem()
  308. rVal := reflect.ValueOf(val)
  309. if !rVal.CanConvert(vElem.Type()) {
  310. // type is not converted
  311. return false
  312. }
  313. vElem.Set(rVal.Convert(vElem.Type()))
  314. return true
  315. }