So in Go I have the following string
["item1", "item2", "item3"]
I want to turn this string into a list containing each items. What is the best way to go about this? Sorry I am still learning Go but couldn't find similar info on this
So in Go I have the following string
["item1", "item2", "item3"]
I want to turn this string into a list containing each items. What is the best way to go about this? Sorry I am still learning Go but couldn't find similar info on this
If your string is JSON (as comments suggest) that has top-level list of objects of same type; you can use encoding/json from standard library to parse and simply unmarshal it into a slice of your Go struct type like this:
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Name string
Foo []string `json:"foo"`
}
func main() {
// Unmarshall to slice
var data []Data
// Your string with list of objects
input := `[{"name": "first", "foo":["item1", "item2", "item3"]}, {"name": "second", "foo":["item5", "item6"]}]`
err := json.Unmarshal([]byte(input), &data)
if err != nil {
panic(err)
}
fmt.Println(data)
}
I recommend reading JSON and Go which pretty much explains how to read JSON and in Go.