Home > Mobile >  Golang Redis Eval return array
Golang Redis Eval return array

Time:12-06

When a Lua script returns a table array during an Eval call, how can it be converted to a []string in go?

The redis cli returns bulk replies in the following format.

  1. val1
  2. val2

Will go-redis eval function return the bulk entries as

["val1", "val2"]

CodePudding user response:

You can use the encoding/json package to convert a JSON string to a slice of strings.

package main

import (
    "encoding/json"
    "fmt"
)

// jsonString is the JSON string that you want to convert to a slice of strings.
const jsonString = `["value1", "value2"]`

func main() {
   
    var stringSlice []string

    // Unmarshal the JSON string into the stringSlice variable.
    err := json.Unmarshal([]byte(jsonString), &stringSlice)
    if err != nil {
        fmt.Println(err)
        return
    }

    
    fmt.Println(stringSlice) // ["value1", "value2"]
}

CodePudding user response:

On Lua (redis-cli, eval) side you can use cjson.encode() to return a table as a json string

eval 'return(cjson.encode({"value1", "value2"}))' 0
"[\"value1\",\"value2\"]"

-- A Function that returns a table can be returned with...
eval 'return(cjson.encode(A_Function_That_Returns_A_Table()))' 0

...if the table key/value datatypes fits json datatypes.
For example, a Lua Function as json value fails.

If it (json string) is not what you want, than more information about the returned table is necessary.

Because on known table structure this is possible...

eval 'return(({"value1", "value2"})[1])' 0
"value1"
eval 'return(({"value1", "value2"})[2])' 0
"value2"
  • Related