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

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

报告相同问题?

悬赏问题

  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 找一个QT页面+目标识别(行人检测)的开源项目
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错