Array Varchar (psql) to array string (golang)

时间:2016-02-12 21:25:15

标签: arrays postgresql go

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 :

public static void vowelCounter(){
    int numVowels = 0;
    System.out.print("Vowels:")
    for (int i = 0; i<strUserResponse.length();i++){
        char v = strUserResponse.charAt(i);
        if (v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u'
          || v == 'A'|| v == 'E' || v == 'I' || v == 'O' || v == 'U'){
            System.out.print(" "+v);
            numVowels++;
        }
    }System.out.print("Number of vowels: "+numVowels);
}

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

tags varchar(50)[] default NULL

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

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

so i apply function of my var rowstag

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

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

var tags := Uint8toString(rowtags)

of course I would like it

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

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

1 个答案:

答案 0 :(得分:0)

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:

$Import.Count - $Sample.Count

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:

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

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 {
     var stringArray []string
     json.Unmarshal(array, &stringArray)
     return stringArray
}