从 types.JSON.TEXT 转换为字符串列表

Dav*_*ham 0 string text json trim go

我有一个 JSON.TEXT (https://godoc.org/github.com/jmoiron/sqlx/types#JSONText),我需要将其转换为字符串列表。例如,如何转换

`["equals", "less than"]` // JSON.TEXT type
Run Code Online (Sandbox Code Playgroud)

["equals", "less than"] // list of strings
Run Code Online (Sandbox Code Playgroud)

我试图通过使用string()、修剪[]括号并将它们连接起来来显式转换 JSON.TEXT 类型,但我最终得到了一个带有奇怪反斜杠的字符串数组:

["\"equal to\"", " \"less than equal to\""]
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以实现此目的,或者如何摆脱反斜杠?

Sar*_*lai 6

从修剪/分割的结果看来,您拥有的变量是

types.JSONText([]byte(`["equals", "less than"]`))
Run Code Online (Sandbox Code Playgroud)

要将其转换为字符串切片,您可以使用 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)
}
Run Code Online (Sandbox Code Playgroud)

这是游乐场的链接:https ://play.golang.com/p/cAiJjWNu8Vx