Search code examples
jsonstringgotexttrim

Convert from types.JSON.TEXT to list of strings


I have a JSON.TEXT (https://godoc.org/github.com/jmoiron/sqlx/types#JSONText) that I need to convert to a list of strings. For instance, how do you convert

`["equals", "less than"]` // JSON.TEXT type

to

["equals", "less than"] // list of strings

I am trying to explicitly convert the JSON.TEXT type by using string(), trimming the [ and ] brackets, and joining them, but I am ending up with an array of strings with weird backslashes:

["\"equal to\"", " \"less than equal to\""]

Is there another way to achieve this, or how can I get rid of the backslashes?


Solution

  • From the result of your trim/split it looks like the variable you have is

    types.JSONText([]byte(`["equals", "less than"]`))
    

    to convert it into a slice of string you can use the json.Unmarshal function

    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)
    }
    

    here is a link to the playground : https://play.golang.com/p/cAiJjWNu8Vx