我有一个JSON.TEXT(https://godoc.org/github.com/jmoiron/sqlx/types#JSONText),我需要将其转换为字符串列表。例如,如何转换
"[equals, less than]" // JSON.TEXT type
到["equals", "less than"] // list of strings
我试图通过使用string()
,修剪[
和]
括号并加入它们来显式转换JSON.TEXT类型,但是最后得到的是带有反斜杠的字符串数组:["\"equal to\"", " \"less than equal to\""]
还有另一种方法可以实现此目的,或者如何摆脱反斜杠?
最佳答案
从修剪/分割的结果来看,您拥有的变量看起来是
types.JSONText([]byte(`["equals", "less than"]`))
要将其转换为字符串 slice ,可以使用json.Unmarshal函数package main
import (
"encoding/json"
"fmt"
"github.com/jmoiron/sqlx/types"
)
func main() {
txt := types.JSONText([]byte(`["equals", "less than"]`))
var slice []string
json.Unmarshal(txt, &slice)
fmt.Println(slice)
}
这是操场的链接:https://play.golang.com/p/cAiJjWNu8Vx
关于json - 从types.JSON.TEXT转换为字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62568701/