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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面