duanke1984 2018-04-06 08:47
浏览 199
已采纳

JSON将数字视为base64 golang

Trying to send query output to browser as JSON, but numbers are treated as Base64. Integers prints out correct.

 var rows *sqlx.Rows 
 enc := json.NewEncoder(w)

 rows, err = db.Queryx(query)
  for rows.Next() {
    results := make(map[string]interface{})
    err = rows.MapScan(results)
    if err := enc.Encode(results); err != nil{
       fmt.Fprintf(w,"%s
", results)
    }
 }

The result from JSON is (id integer, qty numeric / float):

{"ID":1,"QTY":"OC4wMA=="}

{"ID":2,"QTY":"OC4wMA=="}

Without JSON encoding, the numeric column is treated correct as numbers.

EDIT

@mkopriva hope this answer helps:

"if you provide the table definition so we can see how the column is defined, it would also help to see the SQL query so we can see how you're pulling the column from the db"

"ID"  int4
"QTY" numeric 

SELECT * FROM table

and it would also help if you provide the code and its output which you mentioned as "treating the columns correctly as numbers"

var rows *sqlx.Rows 

rows, err = db.Queryx(query)
for rows.Next() {
  results := make(map[string]interface{})
  err = rows.MapScan(results)
  fmt.Fprintf(w,"%s
", results)
}

Gives this result:

map[ID:1 QTY:9.75]

map[ID:2 QTY:7.00]

"can you do fmt.Printf("%T", results["QTY"]) for us? It is highly doubtful that if "QTY" is truly an int or float that the json encoder would marshal it as a base64 string.

without JSON this gives:

[]uint8 []uint8

  • 写回答

2条回答 默认 最新

  • dream0614 2018-04-21 14:20
    关注

    After countless attempts, I found a solution that solves the problem by converting numbers to strings. Not ideal, but rather simple.

    var rows *sql.Rows
    rows, err = db.Query(query)
    cols, _ := rows.Columns()
    colnames, _ := rows.Columns()
    vals := make([]interface{}, len(cols))
    
    for i, _ := range cols {  //bytes to string
       vals[i] = &cols[i]
    }
    
    mymap := make(map[string]interface{})
    
    for i, v := range vals {  //adding column names
      mymap[colnames[i]] = v
    }
    
    for rows.Next() {
       err = rows.Scan(vals...)
       json, _ := json.Marshal(mymap)
       fmt.Fprintf(w,"%s
    ",json)
    }
    

    Feel free to downvote, but please do me the honour to explain why.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧