json对象转slice
package mainimport ( "encoding/json" "fmt" "github.com/gogf/gf/container/garray"
) func main ( ) { jsonStr := `["apple", "banana", "orange"]` var data interface { } if err := json. Unmarshal ( [ ] byte ( jsonStr) , & data) ; err != nil { fmt. Println ( "解析 JSON 失败:" , err) return } array, ok := data. ( [ ] interface { } ) if ! ok { fmt. Println ( "无法转换为 g.Array" ) return } g. Dump ( array)
content, _ := gjson. LoadContent ( jsonStr) array := content. Array ( ) g. Dump ( array) }
slice转garray
slice := [ ] string { "apple" , "banana" , "orange" }
gArray := garray. New ( ) for _ , v := range slice { gArray. Append ( v) }
garray := garray. NewStrArrayFrom ( slice) g. Dump ( garray. Slice ( ) ) fmt. Println ( gArray. Slice ( ) ) contains := garray. Contains ( "apple" ) g. Dump ( contains)
json转map和gmap
package mainimport ( "encoding/json" "fmt"
)
func main ( ) { jsonStr := `{"name": "John", "age": 30, "city": "New York"}` var data map [ string ] interface { } if err := json. Unmarshal ( [ ] byte ( jsonStr) , & data) ; err != nil { fmt. Println ( "解析 JSON 失败:" , err) return }
content, _ := gjson. LoadContent ( jsonStr) data := content. Map ( ) fmt. Println ( data) gMap := gmap. NewFrom ( data) fmt. Println ( gMap)
}
判断指定字符串是否在数组里面
findStr := 3 familyIds := "3,4" idsArr := gstr. Split ( familyIds, "," ) for _ , id := range idsArr { if id == gconv. String ( findStr) { err = gerror. New ( "已加入" ) return } } idsArr := gstr. Split ( familyIds, "," ) var gArr garray. StrArraygArr. Append ( idsArr... ) fmt. Println ( gArr. Contains ( findStr) )
省市区json数据转换
dataJson := `{"code": "110000","value": "北京市","children": [{"code": "110100","value": "北京市","children": [{"code": "110101","value": "东城区"},{"code": "110102","value": "西城区"}]}]}` type Area struct { Code string Value string Children [ ] Area} var area * AreajsonObj := gjson. New ( dataJson) jsonStr := jsonObj. String ( ) err = json. Unmarshal ( [ ] byte ( jsonStr) , & area) if err != nil { fmt. Println ( "转换失败:" , err) return } g. Dump ( "area" , area) j, _ := gjson. LoadContent ( dataJson) j. Scan ( & area) g. Dump ( "area" , area)