doushang1890 2018-07-18 06:20
浏览 2039

在Golang中从MySql读取Json数据?

I am facing a case where I had to store dynamic values in the database with key and value pairs given by the user itself.

User gives the key and value, and I interpret it as

{"key": "user Given", "value": "user Given"}

and I add all such things to an array, and I want this array to be read into Go code where the array of objects is read from the Database table.

  • 写回答

1条回答 默认 最新

  • doujie3888 2018-07-18 09:47
    关注

    A quick hack, not necessarily the most elegant approach, is to use Golang's default JSON Unmarshaler behavior for golang maps:

    jstr := `{"key": "userKeyValue", "value": "userValueValue"}`
    
    // declare a map that has a key string and value interface{} so that any values or
    // types will be accepted;
    jmap := make(map[string]interface{})
    
    err := json.Unmarshal(jstr, &jmap)
    if err != nil {
        log.Fatal(err)
    }
    
    for k, v := range jmap {
        fmt.Printf("Key: %v, Value: %v
    ", k, v)
        // If you want to directly work with v remember it is an interface{}
        // Thus to use it as a string you must v.(string)
    }
    // Will output the following:
    // Key: key, Value: userKeyValue
    // Key: value, Value: userValueValue
    

    You can now use standard golang map to manipulate or manage the received data... The more elegant approach is to implement the JSON Marshaler and Unmarshaler interfaces for your declared type. These are described in the golang documentation: https://golang.org/pkg/encoding/json/

    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大