Rows to map to JSON using sqlx package

huangapple go评论92阅读模式
英文:

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".

huangapple
  • 本文由 发表于 2014年7月15日 15:56:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/24752814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定