Home > Back-end >  Golang convert string in to an array
Golang convert string in to an array

Time:07-18

I have a string that I want to convert into an array.

str := "[\"firsName\",\"lastName\", \"email\"]"
fmt.Println(reflect.TypeOf(str))
fmt.Println(strings.Split(str, ","))

This results:

[["firsName" "lastName"  "email"]]

I want the output like this:

["firsName" "lastName"  "email"]

I can get this by using strings.Replace function. But is there any better way to do this?

Go Playground: https://go.dev/play/p/HYr7ILt74OW

CodePudding user response:

You can use strings.Trim to remove the trailing and leading unwanted character.

trimmedStr := strings.Trim("[\"firsName\",\"lastName\", \"email\"]", "[]")
fmt.Println(strings.Split(trimmedStr, ","))

CodePudding user response:

str := "[\"firsName\",\"lastName\", \"email\"]"
var strArr []string
_ = json.Unmarshal([]byte(str), &strArr)
fmt.Println(strArr)
  • Related