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

在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/

    评论

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析