map.go 9.1 KB

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