英文:
Rows to map to JSON using sqlx package
问题
尝试将结果转换为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{}{}
// 遍历行
rows, err := db.Queryx("SELECT id,cname FROM items")
for rows.Next() {
err := rows.MapScan(m)
if err != nil {
log.Fatal(err)
}
}
// 将map转换为JSON
b, _ := json.Marshal(m)
// 打印结果的JSON
fmt.Printf("Marshalled data: %s\n", b)
}
输出结果为Marshalled data: {"cname":"c29tZWl0ZW0","id":"MA=="}
,但应该是Marshalled data: {"cname":"someitem","id":0}
。我不确定如何解决这个问题,因为返回的值是以base64
编码的,有什么想法吗?
英文:
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
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=="}
and it should be Marshalled data: {"cname":"someitem","id":0}
and I am not sure how to go around this since the values returned in base64
encodig, any ideas?
答案1
得分: 4
只需在遍历地图之前对base64字符串进行解码,然后再进行地图的编组:
import (
"encoding/base64"
"encoding/json"
"log"
)
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)
你需要在导入部分添加这行代码:"encoding/base64"
。
英文:
Just iterate over your map and decode the base64 strings prior to marshal the map:
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"
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论