使用sqlx包映射到JSON的行

时间:2022-12-02 21:10:42

Trying to get the result into a JSON string, I have to use MapScan because i have no structs that represent the data so here is what i did

试图将结果转换为JSON字符串,我必须使用MapScan,因为我没有表示数据的结构,所以这就是我所做的

import (
    "fmt"
    "log"
    "encoding/json"
    _ "github.com/jmoiron/sqlx"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sqlx.Connect("mysql", "uname:pwd@/db")
    if err != nil {
        log.Fatal(err)
    }

    m := map[string]interface{}{}

    //Go through rows
    rows, err := db.Queryx("SELECT id,cname FROM items")
    for rows.Next() {
        err := rows.MapScan(m)
        if err != nil {
            log.Fatal(err)
        }
    }

    //Marshal the map
    b, _ := json.Marshal(m)

    //Prints the resulted json
    fmt.Printf("Marshalled data: %s\n", b)
}

The output is Marshalled data: {"cname":"c29tZWl0ZW0","id":"MA=="}

输出是Marshalled数据:{“cname”:“c29tZWl0ZW0”,“id”:“MA ==”}

and it should be Marshalled data: {"cname":"someitem","id":0}

它应该是Marshalled数据:{“cname”:“someitem”,“id”:0}

and I am not sure how to go around this since the values returned in base64 encodig, any ideas?

我不确定如何绕过这个,因为base64编码返回的值,任何想法?

1 个解决方案

#1


4  

Just iterate over your map and decode the base64 strings prior to marshal the map:

在编组地图之前,只需迭代地图并解码base64字符串:

for k, encoded := range m {
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
            log.Fatal("error:", err)
    }
    m[k] = decoded
}

b, _ := json.Marshal(m)

You must add this to your imports : "encoding/base64".

您必须将此添加到导入:“encoding / base64”。

#1


4  

Just iterate over your map and decode the base64 strings prior to marshal the map:

在编组地图之前,只需迭代地图并解码base64字符串:

for k, encoded := range m {
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
            log.Fatal("error:", err)
    }
    m[k] = decoded
}

b, _ := json.Marshal(m)

You must add this to your imports : "encoding/base64".

您必须将此添加到导入:“encoding / base64”。