读取外部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?

doudou_0624
「已注销」 不,Go中没有魔术。不过,您可以编写一个函数来为您执行此操作。
大约一年之前 回复

3个回答

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)
    }
}
dq804806
dq804806 我将数据重命名为项目,并将文件重命名为数据,以使示例清晰易懂。 “文件”通常用于指代某些存储上的命名实体。
大约一年之前 回复

You can unmarshal any JSON data in this way:

var data interface{}
if err := json.Unmarshal(..., &data); err != nil {
    // handle error
}

Though, in this way you should handle all the reflection-related stuffs since you don't know what type the root data is, and its fields. Even worse, your data might not be map at all. It can be any valid JSON data type like array, string, integer, etc.

Here's a playground link: https://play.golang.org/p/DiceOv4sATO

It's impossible to do anything as simple as in Python, because Go is strictly typed, so it's necessary to pass your target into the unmarshal function.

What you've written could otherwise be shortened, slightly, to something like this:

func UnmarshalJSONFile(path string, i interface{}) error {
    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer f.Close()
    return json.NewDecoder(f).Decode(i)
}

But then to use it, you would do this:

func main() {
    data := Data{}
    if err := UnmarshalJSONFile("/path/to/file.json", &data); err != nil {
        panic(err)
    }
}

But you can see that the UnmarshalJSONFile is so simple, it hardly warrants a standard library function.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐