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

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

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架