dqp10099 2017-06-02 07:22
浏览 65
已采纳

实现Scan接口将json数组读入map

I am fetching a JSON array from PostgreSQL, and I would like to read it into a map. I am able to Unmarshal the values into a []string slice, but what I actually want is a map[string]bool.

I've written a custom type for the column with a Scan interface that converts the JSON array into a slice of strings first, then reads each string into the custom map type as keys.

type custMap map[string]bool

func (m *custMap) Scan(src interface{}) error {
  b, ok := src.([]byte)
  if !ok {
    return error(errors.New("Error Scanning Array"))
  }

  s := make([]string, 0)
  json.Unmarshal(b, &s)
  for _, v := range s {
    (*m)[v] = true
  }

  return nil
}


type data struct {
  vals custMap `json: "vals"`
}

The query I am trying to scan returns a row with a column vals which is a JSON array: ["some", "arr", "vals"], where the custom type is used like so:

var d models.data
sqlDB.QueryRow().Scan(&d.vals)

My expected output is a struct with the following shape

{ vals: map[string]bool { "some": true, "arr": true, "vals": true }

This compiles fine, but my code panics with "assignment to entry in nil map"

How can I fix my Scan function? Is it even possible to do this with a map type?

  • 写回答

2条回答 默认 最新

  • douying6206 2017-06-02 07:55
    关注

    You are calling your method Scan of type *custMap on a unitialised map. Initialize d.vals either like

    d.vals = custMap{}
    

    or

    d.vals = make(custMap)
    

    Other answers already provide an explanation.

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

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器