doushishi2415
2019-07-11 14:45
采纳率: 0%
浏览 164
已采纳

读取外部JSON文件

I am trying to read the following JSON file:

{
    "a":1,
    "b":2,
    "c":3
}

I have tried this but I found that I had to write each field of the JSON file into a struct but I really don't want to have all my JSON file in my Go code.

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
)

type Data struct {
    A string `json:"a"`
    B string `json:"b"`
    C string `json:"c"`
}

func main() {
    file, _ := ioutil.ReadFile("/path/to/file.json")
    data := Data{}

    if err := json.Unmarshal(file ,&data); err != nil {
        panic(err)
    }
    for _, letter := range data.Letter {
        fmt.Println(letter)
    }
}

Is there a way to bypass this thing with something like json.load(file) in Python?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • douyu7618 2019-07-11 14:48
    最佳回答

    If you only want to support integer values, you could unmarshal your data into a map[string]int. Note that the order of a map is not defined, so the below program's output is non-deterministic for the input.

    package main
    
    import (
        "fmt"
        "encoding/json"
        "io/ioutil"
    )
    
    func main() {
        file, _ := ioutil.ReadFile("/path/to/file.json")
        var data map[string]int
    
        if err := json.Unmarshal(file ,&data); err != nil {
            panic(err)
        }
        for letter := range data {
            fmt.Println(letter)
        }
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题