duanliushua5026 2016-02-12 21:25
浏览 317

数组Varchar(psql)到数组字符串(golang)

I would like to know how i can get my array varchar in my psql database in array string in go for render it in json.

I actually do that

In creation of my table i create my column like that :

tags varchar(50)[] default NULL

when i use my select request for get it in golang :

var rowtags []uint8
err = rows.Scan(&rowtags)
if err != nil {
    log.Fatal(err)
}

i have try to make a fonction that transform uint8[] to string[]

func Uint8toString(array []uint8) []string {

    var ret = make([]string, len(array))
    for i := 0; i < len(array); i++{
        ret[i] = string(array[i])
    }
    return (ret)
}

so i apply function of my var rowstag

var tags := Uint8toString(rowtags)

and when i render struct where var tags is, I get that

  "Tags": [
    "{",
    "#",
    "c",
    ",",
    "#",
    "c",
    ",",
    "#",
    "c",
    "o",
    "u",
    "c",
    "o",
    "u",
    ",",
    "#",
    "c",
    "d",
    "}"
  ],

of course I would like it

  "Tags": [
    "#c",
    "#c",
    "#coucou",
    "#cd"
  ],

thank's for helping me , I'm on golang a short time , and I find no solution.

  • 写回答

1条回答 默认 最新

  • dtu72460 2016-02-12 22:03
    关注

    First of all, why do you have an column called tags that contains multiple tag values? Wouldn't it be better to have another table with a foreign key to the one that tags column is currently in so that each tag value is it's own row? If you have that, you should be able to do something really easy like:

    rows := db.QueryRow("SELECT tag from tags_table where foreign_key = 123")
    var asSlice []string
    err := row.Scan(&asSlice) 
    

    If you have to put it all inside of one column, would it be possible to just store it as JSON? Then you could use the "encoding/json" package do something simple like:

    func Uint8toString(array []uint8) []string {
         var stringArray []string
         json.Unmarshal(array, &stringArray)
         return stringArray
    }
    

    Although I think you should rethink the way you are implementing the above tags column, you could also use the following logic to parse it into strings but it assumes that the format will always be similar to what you've posted:

    func Uint8toString(array []uint8) []string {
        stringNoBrackets := string(array[1:len(array)-1])
        return strings.Split(stringNoBrackets,",")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器