dongmi1221 2018-04-18 21:27
浏览 76
已采纳

将json文件传递给GoLang函数

Just getting started with Go.

I have a Go function as below to which I have to pass a json file. How can I pass a json file reference to this function i.e. accept it as a map of interfaces?

func compressOIds(mapDocument map[string]interface{}) string {
    var objectIdValue string
    for key, value := range mapDocument {
       ....
    }
    return ""
}
  • 写回答

1条回答 默认 最新

  • dtx6087 2018-04-18 21:41
    关注

    If the structure of your JSON is not well defined and can change, that's the way to go:

    import (
        "fmt"
        "encoding/json"
    )
    
    func main() {
        var b = []byte(`{"a":"b", "c":1, "d": ["e", "f"]}`)
        var j map[string]interface{}
        err := json.Unmarshal(b, &j)
        if (err != nil) {
            return
        }
    
        printJson(j)
    }
    
    func printJson(j map[string]interface{}) {
    
        for k, v := range j {
            fmt.Printf("%v %v
    ", k, v)
        }
    }
    

    If your JSON is well defined, though, you can unmarshal it into struct, which is usually better:

    import (
        "fmt"
        "encoding/json"
    )
    
    type Message struct {
        A string
        C int
        D []string
    }
    
    func main() {
        var b = []byte(`{"a":"b", "c":1, "d": ["e", "f"]}`)
        var j Message
        err := json.Unmarshal(b, &j)
        if (err != nil) {
            return
        }
    
        printJson(j)
    }
    
    func printJson(j Message) {
        fmt.Printf("A %v
    ", j.A)
        fmt.Printf("C %v
    ", j.C)
        fmt.Printf("D %v
    ", j.D)
    }
    

    You can play with later code here: https://play.golang.org/p/wDPy4m2x2_t

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面