在 Go 中迭代 json 数组以提取值

Iterate over json array in Go to extract values

我的 json 数组(conf.json 文件)中有以下内容。

{
  "Repos": [
      "a",
      "b",
      "c"
  ]
}

我正在尝试阅读此 json 然后遍历它但卡住了。我是新手(和编程)所以我很难理解这里发生的事情。

import (
    "encoding/json"
    "fmt"
    "os"
)

type Configuration struct {
    Repos []string
}

func read_config() {
    file, _ := os.Open("conf.json")
    decoder := json.NewDecoder(file)
    configuration := Configuration{}
    err := decoder.Decode(&configuration)
    if err != nil {
        fmt.Println("error:", err)
    }

    fmt.Println(configuration.Repos)
}

到目前为止,这是我所能得到的。这将打印出正确的值,[a, b, c].

我想做的是能够遍历数组并单独拆分每个值,但没有任何运气可以做到这一点。我对此采取了错误的方法吗?有更好的方法吗?

你的意思是这样的:

for _, repo := range configuration.Repos {
    fmt.Println(repo)
}

请注意,您示例中的代码不应与您提供的 JSON 一起使用。 valueRepos 之间没有映射关系。您发布的 JSON 不正确,或者在 Configuration 结构上省略了一个标记以正确映射它。

一切正常,只是您的打印没有达到您的预期。由于 Repos 是一个数组,您必须迭代它才能单独打印每个值。尝试这样的事情;

for _, repo := range configuration.Repos {
    fmt.Println(repo)
}