I receive from a Redis store a 2D array as string:
func main() {
client := setRedisClient()
data, err := client.Get(redisKey).Result()
// store data as a 2D slice
}
Here is an example of what data might look like:
[["a", "b"], ["c", "d"], ["e", "f"]]
Ideally, I'd like to be able to have a 2D slice since I need to be able to use indices:
dataAsSlice := [][]string {{"a", "b"}, {"c", "d"}, {"e", "f"}}
fmt.Println(dataAsSlice[0][0]) => "a"
I haven't found a way to parse a response from redis and store is as a 2D slice.
How could I achieve this? Is even storing is as a 2D slice the best way?
Since your string is JSON, you can convert it to a [][]string{}
by using json.Unmarshal
as follows:
str := `[["a", "b"], ["c", "d"], ["e", "f"]]`
var dataAsSlice [][]string
err := json.Unmarshal([]byte(str), &dataAsSlice)
You can see this in action on Go Playground: https://play.golang.org/p/NEpIKc9Fl-s