@@ -7,6 +7,8 @@ package utils
77
88import (
99 "encoding/json"
10+ "regexp"
11+ "strconv"
1012 "strings"
1113)
1214
@@ -28,6 +30,49 @@ func StringToArray(sliceStr string) []string {
2830 return items
2931}
3032
33+ func GetJsonByPath (path string , data interface {}) (interface {}, bool ) {
34+ // Split into parts by `.` and `[]`
35+ re := regexp .MustCompile (`\.|\[|\]` )
36+
37+ parts := re .Split (path , - 1 )
38+
39+ cleaned := []string {}
40+
41+ for _ , part := range parts {
42+ if part != "" {
43+ cleaned = append (cleaned , part )
44+ }
45+ }
46+
47+ current := data
48+
49+ for _ , key := range cleaned {
50+ switch currentDataType := current .(type ) {
51+ // Case: Dictionary
52+ case map [string ]interface {}:
53+ value , ok := currentDataType [key ]
54+ if ! ok {
55+ return nil , false
56+ }
57+ current = value
58+
59+ // Case: Array
60+ case []interface {}:
61+ index , err := strconv .Atoi (key )
62+
63+ if err != nil || index < 0 || index >= len (currentDataType ) {
64+ return nil , false
65+ }
66+ current = currentDataType [index ]
67+
68+ default :
69+ return nil , false
70+ }
71+ }
72+
73+ return current , true
74+ }
75+
3176func GetJsonSafe [T any ](jsonStr string ) (T , error ) {
3277 var result T
3378
@@ -46,4 +91,20 @@ func GetJson[T any](jsonStr string) (T) {
4691 }
4792
4893 return result
94+ }
95+
96+ func ToJsonSafe [T any ](obj T ) (string , error ) {
97+ bytes , err := json .Marshal (obj )
98+
99+ return string (bytes ), err
100+ }
101+
102+ func ToJson [T any ](obj T ) string {
103+ bytes , err := json .Marshal (obj )
104+
105+ if err != nil {
106+ // JSON is empty
107+ }
108+
109+ return string (bytes )
49110}
0 commit comments