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 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件