douyan6871 2019-01-12 16:42
浏览 125
已采纳

如何将Postgresql JSON类型转换为Golang本机?

I am trying to convert a postgres column that is of type json to golang json object.

type MY_JSON struct {
  MY_ID string `json:"my_id"`
  MY_INFO []MY_INNER_JSON `json:"my_info"`
}

type MY_INNER_JSON struct {
    SOME_ID   string `json:"some_id"`
    SOME_NUM  int64 `json:"some_num"`
    SOME_OPTIONAL  string `json:"some_optional,omitempty"`
}

rows, err := db.Query("SELECT my_json FROM my_json_table LIMIT 1;")

for rows.Next() {
    var mycolumn MY_JSON
    err = rows.Scan(&mycolumn)
    fmt.Println(mycolumn)
}

This is what the json looks like

{
    "my_id": "this is my_id",
    "my_info": [
        {
            "some_id": "some_id",
            "some_num": 123
        },
        {
            "some_id": "some_id",
            "some_num": 123,
            "some_optional": "sometimes more"
        },
    ]
}

I am getting panic from golang during runtime.

Can someone point me a direction and tell me where I am doing wrong?

  • 写回答

1条回答 默认 最新

  • dpt62283 2019-01-12 17:02
    关注

    By implementing the sql.Scanner interface on MY_JSON, your code should work as is. To do this, you need only to add the Scan method on the MY_JSON type (with pointer receiver).

    func (m *MY_JSON) Scan(src interface{}) error {
        bs, ok := src.([]byte)
        if !ok {
            return errors.New("not a []byte")
        }
        return json.Unmarshal(bs, m)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 python如何用抖音这个接口输入抖音ID查询用户信息
  • ¥30 关于移动Web网页使用TinyMCE富文本编辑器上传图片后的光标定位、压缩等几个问题如何解决:
  • ¥25 activeMq在同服务器centos8下消费很慢
  • ¥20 为什么zynq CAN IP 无法进入config配置模式,XCan_SelfTest函数失效?
  • ¥15 Pycharm中程序直接运行可以但进入调试报错
  • ¥15 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥15 我的显卡支持CUDA最高版本是12.3,这个版本也支持VS 2022 17.0这种情况下如果我想下载CUDA11.8,需要下载旧版本的VS2022吗
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!