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条)

报告相同问题?

悬赏问题

  • ¥70 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。