kiran
kiran

Reputation: 444

Golang convert string in to an array

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

Upvotes: 1

Views: 1856

Answers (2)

Mufaddal Tahir
Mufaddal Tahir

Reputation: 539

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

Upvotes: 0

davidriod
davidriod

Reputation: 1037

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

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

Upvotes: 3

Related Questions