1

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

2
  • 3
    The example string is valid json, so you could just use json.Unmarshal with []string as the target argument. go.dev/play/p/sxFpIHiFbaW Commented Jul 18, 2022 at 6:38
  • instead of split use trim fmt.Println(strings.Trim(str, ",")) Commented Jul 18, 2022 at 7:59

2 Answers 2

3

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

trimmedStr := strings.Trim("[\"firsName\",\"lastName\", \"email\"]", "[]")
fmt.Println(strings.Split(trimmedStr, ","))
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.