doumeilmikv7099 2018-04-04 13:41
浏览 237
已采纳

我如何以json格式输出map [string] interface {}?

I have a problem with formatting when using sqlx

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

The output when using %#v

fmt.Fprintf(w,"%#v 
", results)

map[string]interface {}{"USER_ID”:”JD”, "USER_NAME”:”John Doe”}

map[string]interface {}{"USER_ID”:”JAD”, "USER_NAME”:”Jane Doe”}

map[string]interface {}{"USER_ID”:”DD”, "USER_NAME”:”Donald Duck”}

Using only %v

fmt.Fprintf(w,"%v 
", results)

map[USER_ID:JD USER_NAME:John Doe]

map[USER_ID:JAD USER_NAME:Jane Doe]

map[USER_ID:DD USER_NAME:Donald Duck]

The desired output is to get rid of map[string]interface {}

{"USER_ID”:”JD”, "USER_NAME”:”John Doe”}

{"USER_ID”:”JAD”, "USER_NAME”:”Jane Doe”}

{"USER_ID”:”DD”, "USER_NAME”:”Donald Duck”}

Is this possible?

EDIT USING JSON

According to @Timothy Jones I have updated the main code and it work as expected. Except that the result is printed to the TERMINAL and not browser.

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

{"USER_ID”:”JD”,”USER_NAME”:”John Doe”}

{"USER_ID”:”JAD”,”USER_NAME”:”Jane Doe”}

{"USER_ID”:”DD”,”USER_NAME”:”Donald Duck”}

Removing the error handling just to test. It shows wrong results, but are printed to the BROWSER as it should.

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

map[USER_ID:JD USER_NAME:John Doe]

map[USER_ID:JAD USER_NAME:Jane Doe]

map[USER_ID:DD USER_NAME:Donald Duck]

One question remains. How do I print the correct result to the BROWSER?

  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 内存管理的一段代码不是很理解
      • ¥20 打开anaconda时卡在Loading applications无法进入界面
      • ¥15 网页超时时间设置失效
      • ¥15 有关绿色信贷毕业论文的问题
      • ¥30 关于#机器人#的问题,如何解决?
      • ¥15 求MATLAB函数ScalarLayerDisplay的代码
      • ¥15 安卓如何自动执行检测到的NFC标签,无需再点确认
      • ¥15 pyHM库mouse模块的ValueError错误
      • ¥15 python opencv 摄像头 传感器
      • ¥30 eMMC&Android&C&Linux