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

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

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算