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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?